I am using following code to add checkbox
in Android Action Bar
:
<item
android:id="@+id/action_checkbox"
app:actionViewClass="android.widget.CheckBox"
android:title="@string/action_check"
app:showAsAction="always"
/>
How can I get the value of above checkbox
whether it is selected or not as Menu item
in android?
You can use isChecked()
to get the checked state of a CheckBox
:
CheckBox checkBox = (CheckBox) findViewById(R.id.action_checkbox);
if(checkBox.isChecked())
// do something
else
// do something else
your java code where you manage checkbox
click event
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
MenuItem check = menu.findItem(R.id.action_checkbox);
CheckBox c_box =(CheckBox) check.getActionView();
c_box.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if(b){
Toast.makeText(getActivity(), "checked",
Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getActivity(), "unchecked",
Toast.LENGTH_SHORT).show();
}
}
});
return true;
}
your menu looks like ok
<item
android:id="@+id/action_checkbox"
app:actionViewClass="android.widget.CheckBox"
android:title="@string/action_check"
app:showAsAction="always"
/>
Hope it works.. let me know if you face any problem.
Please Refer to Documentation for simple questions like these.
Also onOptionsItemSelected is part of Menu.
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.