Android's ToggleButton setChecked(…) method not changing status of button

余生长醉 提交于 2019-12-09 01:26:21

问题


I have a togglebutton which is not responding to my setChecked(...) method. Here is the code:

mBool = mPrefs.getBoolean("buttondefault", true);
Boolean b = mBool; //Only creating this for Logging, mBool IS PRIMITIVE
Log.e("Update pref", b.toString());
mToggle = (ToggleButton)findViewById(R.id.ac_toggle);
mToggle.setOnClickListener(this);
mToggle.setChecked(mBool);

The log reports mBool to be true, let when I do mToggle.setChecked(mBool) the button remains in the off position.

Here is the xml for the button:

<ToggleButton android:id="@+id/ac_toggle"
android:textOn="Yes"
android:textOff="No"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="3sp"
android:layout_weight="5"/>

Any ideas?


回答1:


Please use primitive boolean to set the state

//set true or false based on your prefs
boolean mBool = true;
mToggle.setChecked(mBool);



回答2:


The code I presented was just copied from different methods. Long story short I was setting the boolean after I initialized and set the button's checked status. Apologies.




回答3:


Possibly need to call View.requestLayout() or View.forceLayout() on the buttons View to refresh the buttons state




回答4:


Because the button's setChecked() method accepts a primitive boolean as parameter. you're supplying a Boolean (wrapper class) variable. Normally that should be fine, however it doesn't work on this specific method, so you might need to manually unbox the variable or change the type of mBool to boolean



来源:https://stackoverflow.com/questions/8025943/androids-togglebutton-setchecked-method-not-changing-status-of-button

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!