Reputation: 50
Im trying to use a checkbox in actionbar,im using actionbarsherlock.
i've tried very hard to get the checkbox work,now I've made the UI (bu using the setCustomView method),but I'm stucked at catch the check event of the checkbox,I did some research of some similar questions but get the answer that "checkbox cant be used in actionbar ,it can only be used in submemus or etc", I doubt that and wondered whether there is a way to get it work...
here is my UI:
here is my CustomView xml file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_gravity="right"
android:gravity="center_vertical" >
<CheckBox
android:id="@+id/action_anoni_check"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_gravity="center_vertical"
android:checked="false"
android:gravity="center"
android:text="@string/anonymity" />
</LinearLayout>
here is how i added it in my ui:
ActionBar actionBar = getSupportActionBar();
actionBar.setCustomView(R.layout.write_actionbar_top);
Upvotes: 0
Views: 1824
Reputation: 3494
I know this is an old question, but I thought I'd chime in because I couldn't get Craig's solution to work correctly. The "intended" approach to do this is:
getSupportActionBar().setDisplayShowCustomEnabled(true);
getSupportActionBar().setCustomView(R.layout.write_actionbar_top);
CheckBox mCheckbox = (CheckBox) getActionBar().getCustomView().findViewById(R.id.action_anoni_check);
mCheckbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
//DO YOUR on CHECK ACTION IN HERE
}
}
});
Upvotes: 1
Reputation: 389
You may want to create a class instance variable and inflate your write_actionbar_top view so you have reference to it, then add a onCheckListener to your checkbox:
private CheckBox mCheckbox;
...
...
mCheckbox = getLayoutInflater().inflate(R.layout.write_actionbar_top, null,false);
mCheckbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
if(isChecked){
//DO YOUR on CHECK ACTION IN HERE
}
}
}
ActionBar actionBar = getSupportActionBar();
actionBar.setCustomView(mCheckbox);
This code hasn't been tested but you should get the idea.
There are also some more ways to get the click or check action on your CheckBox view here -> Android: checkbox listener
Upvotes: 0