简体   繁体   中英

How to overwrite a text in TextView using a button?

I'm working on an app that generates passwords randomly using the array. The password is in TextView. Everything is good unless I want to generate a new password second time. How can I "delete" the old text (password) from the TextView and replace it with the new one using the same button?

Here are the variables that I'm using:

EditText dlugosc;
String haslo = "";
String pustak = "";
TextView haslo0;

And this is a code that I use to generate a password:

(znaki is the name of array)

dlugosc = findViewById(R.id.password_len);
haslo0 = findViewById(R.id.password);
String yui = dlugosc.getText().toString();
int x = Integer.parseInt(yui);
for(int i = 0; i < x; i++){
    int Index = generator.nextInt(znaki.length);
    haslo = znaki[Index] + haslo;
}

I have already tried doing an if structure:

if (haslo0 != null){
   haslo0.setText(pustak);
   haslo0.setText(haslo);
}
else
   haslo0.setText(haslo);

But it doesn't help :(

When I want to have 7 chars in the password and click the button first time, the result is correct eg PKAjzQL . But when I click the button second time, the result is nBzcRjQPKAjzQL instead of nBzcRjQ .

How can I "delete" the old text (password) from the TextView and replace it with the new one using the same button?

The problem is not to "delete" the old text, the problem is that you have to clear the list for example, every time user clicks on the Button you clear the list doing : znaki.clear() , then it will only show the new password generated.

If you see your output :

First output :

PKAjzQL --> This is correct

Second output :

nBzcRjQPKAjzQL --> this is the new output + the old one

Can you give the code of the OnClickButton? And why are you setting the same TextView with diferents Strings when you click?

 haslo0.setText(pustak);
 haslo0.setText(haslo);

?

Why are you appending the old string haslo behind the newly generated one in haslo = znaki[Index] + haslo; Probably that's why you are getting output like that. Can you please try just setting newly generated password into the textview like haslo = znaki[Index];

And then try to set text in the text view using haslo0.setText(haslo);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM