Shankar S Shankar S - 4 months ago 13
Android Question

android toggle button state always true

Been trying to use a

ToggleButton
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
onCreateView()
as below:

bmark = (ToggleButton) v.findViewById(R.id.bmark);
bmark.setChecked(false);


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

public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);

bmark.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
boolean status;
if (bmark.isChecked()) status = true;
else status = false;
Log.w("Bmark status",String.valueOf(status));
if (status) {
bmark.setChecked(false);
Log.w("Bmark after true",String.valueOf(bmark.isChecked()));
Toast.makeText(getActivity(), "Bookmark removed!", Toast.LENGTH_SHORT).show();
} else {
bmark.setChecked(true);
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
setChecked(false)
, 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

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.

Comments