Shankar S Shankar S - 1 year ago 113
Android Question

android toggle button state always true

Been trying to use a

to act as a bookmark kind of thing in my application. I am using this for the first time. I have declared my toggle button under
as below:

bmark = (ToggleButton) v.findViewById(;

I am trying to just toggle the state and show a
message! I tried the below:

public void onActivityCreated(Bundle savedInstanceState) {

bmark.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
boolean status;
if (bmark.isChecked()) status = true;
else status = false;
Log.w("Bmark status",String.valueOf(status));
if (status) {
Log.w("Bmark after true",String.valueOf(bmark.isChecked()));
Toast.makeText(getActivity(), "Bookmark removed!", Toast.LENGTH_SHORT).show();
} else {
Log.w("Bmark after false",String.valueOf(bmark.isChecked()));
Toast.makeText(getActivity(), "Post Bookmarked..!", Toast.LENGTH_SHORT).show();


Every time I press the button, the status is initially read "true", although I've set it to "false". After I call
, it also becomes false. But when I click it again, it again reads "true" and instead of "false"

I dont know why its happening like this. I just want to toggle it every time I click it. Pls help me out! Thanks in advance :)

Answer Source

Change code to:

if (bmark.isChecked()){ 
status = true;
Toast.makeText(getActivity(), "Post Bookmarked..!",Toast.LENGTH_SHORT).show();
else {
status = false;
Toast.makeText(getActivity(), "Bookmark removed!", Toast.LENGTH_SHORT).show();

Toggle changes self checked status, You done that again so status was changed two times.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download