简体   繁体   中英

android toggle button state set texview text

i have a toggle button which when set to the on position sets the hint to one of my textview to

"kg"

. the initial hint of the text view is

"st"

which should be shown if the toggle is in the off position.

when i first start the app the textview dispalys

"st"

(which at first is ok as the toggle is in the off position) now when i press the toggle it turns to the on position and displays

"kg"

in the textView (this is also ok.)

now comes the problem. if i click on the toggle again (off position) the textView stays as

"kg"

does anyone know how i could set it to always display "st in the off state and "kg" in the on state.

many thanks in advance

addListenerOnButton();

      }

      public void addListenerOnButton() {

        unitToggle = (Button) findViewById(R.id.unitToggle);
       final TextView tw1 = (TextView)findViewById(R.id.tw1);


        unitToggle.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {

               StringBuffer result = new StringBuffer();
               tw1.setHint("kg");
 unitToggle.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {

           StringBuffer result = new StringBuffer();
           if(tw1.getHint().toString().equals("kg"))
                tw1.setHint("st");             
           else
                tw1.setHint("kg");

The main reason for the said problem is the logic which has not yet been implemented.

When you click the button for the first time it sets the text to "kg" which it will set always on any number of click. since you have written the statement

tw1.setHint("kg");

inside your onClick() method without keeping the state of the button. emphasized text .

In order to make it correct use a boolean flag and change its state on each click and set the text based on the flag value.

The best way to do it is to use ToggleButton which has the inbuilt on/off states so you don't need to have your on boolean flag and set the hint based on the button state.

Try

private boolean on=false;

 unitToggle.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {

           StringBuffer result = new StringBuffer();
           if(on){
                tw1.setHint("kg");
                on = true;
           }else{
               tw1.setHint("st");
               on = false;
           }

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