简体   繁体   中英

On Button click i want to toggle the text of TextView

I want to toggle textview text with on a button click .I have set the flag as public variable and change it in onclick function but still the value of flag for some reason is initialized to its default value. i am beginner to android studio Thank you.

public class MainActivity extends AppCompatActivity {
public Button bt1;
public TextView txt;
public boolean flag;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    bt1=(Button) findViewById(R.id.button);
    txt=(TextView) findViewById(R.id.textView2);


    bt1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(flag){
                flag=false;
                txt.setText("Steve");
            }
            else {
                txt.setText("Shetty");
                flag=true;
            }

        }
    });

 }
 }

I want text of Textview to toggle every time i click on the button but text of textview changes only once.

flag is Always true and the text is Always set to "Steve"

flag=true;
if(flag=true){
flag=false;
txt.setText("Steve");
}
else {
txt.setText("Shetty");
flag=true;
}

try to initialize flag with true and remove the flag = true part inside your onClickListener

flag = true;
bt1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {

if(flag=true){
flag=false;
txt.setText("Steve");
}
else {
txt.setText("Shetty");
flag=true;
}

}
});

That is because you defined the variable "flag" in the local scope. Meaning that when you modify the flag variable and you go out of the local scope (exiting the onClick method), the flag variable no longer exists. So the change that you made is not reflected the next time it goes to the onClick method. (You are also setting the value of the variable at the start, so of course the if statement always evaluates to True) To fix this problem, define the flag variable outside of onClick() method where it is accessible.

boolean flag;

bt1.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        if(flag){
            flag=false;
            txt.setText("Steve");
        }
        else {
            txt.setText("Shetty");
            flag=true;
        }

    }
});

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