How to add CheckBox to Toolbar?
Asked Answered
I

2

5

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.

Inductee answered 26/9, 2015 at 9:57 Comment(4)
Try changing android:actionViewClass to app:actionViewClass.Carolann
@Sameer Nice, it shows the CheckBox, but no text .. :)Inductee
Why don't you use : app:showAsAction = "always" ; probably it's not enough space and the text goes awayBranch
@Lazai, tried it, didn't workInductee
C
11

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;
}
Carolann answered 26/9, 2015 at 12:29 Comment(2)
I want it to be action, I don't want it in the menu itself but over the toolbarInductee
Please check if it serves your purpose. I have verified it to show the text with checkbox.Carolann
T
1

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;
}
Tarnation answered 24/1, 2020 at 3:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.