Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add CheckBox to Toolbar?

I've tried using the following code but no checkbox appear, only text :

<item
    android:id="@+id/menuShowDue"
    android:actionViewClass="android.widget.CheckBox"
    android:title="@string/string_due"
    android:checkable="true"
    app:showAsAction="ifRoom" />

Is it not possible to add it via menu ? Should I do something else ?

I'm using android.support.v7.widget.Toolbar as Toolbar.

like image 316
SagiLow Avatar asked Dec 14 '22 11:12

SagiLow


2 Answers

Please make changes as shown below to app:actionViewClass and app:showAsAction and it should work for you.

<item
    android:id="@+id/menuShowDue"
    android:checkable="true"
    android:title="@string/string_due"
    app:actionViewClass="android.widget.CheckBox"
    app:showAsAction="ifRoom|withText" />

Also make the relevant changes to onCreateOptionsMenu(). Sample text pasted below;

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);

    CheckBox checkBox = (CheckBox) menu.findItem(R.id.menuShowDue).getActionView();
    checkBox.setText("Sample Text");
    return true;
}
like image 95
Sameer Khan Avatar answered Jan 15 '23 18:01

Sameer Khan


You can set the title at OnCreateOptionsMenu. Use MenuItem should be sufficient.

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);

    MenuItem checkBoxMenuItem =  menu.findItem(R.id.menuShowDue);
    checkBoxMenuItem.setTitle("Sample Text");
    return true;
}

In OptionsItemSelected, check if checkbox selected or not:

public boolean onOptionsItemSelected(MenuItem item)
{
    switch (item.getItemId())
    {
    case R.id.menuShowDue:
        if(item.isChecked())
        {
            item.setChecked(false);
        }else{
            item.setChecked(true);
        }
        break;
}
like image 45
mhcpan Avatar answered Jan 15 '23 18:01

mhcpan