How to add checkboxes in Android App toolbar?

2019-09-11 08:43发布

问题:

I need to add a Checkbox in Android App bar. my Menu_main as follow:

<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools" tools:context=".MainActivity">

<item android:id="@+id/action_search"
    android:title="search"
    android:icon="@drawable/ic_search"
    app:showAsAction="ifRoom|collapseActionView"
    app:actionViewClass="android.support.v7.widget.SearchView" />

</menu>

Right now it's showing Title and search icon. How can I add a Checkbox in Bar right next to Search icon?

回答1:

There are two ways to add CheckBox in menu . 1. User direct class (Action View) e.g

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".tariff.ui.SearchOffersActivity">
    <item
        android:id="@+id/action_search"
        android:icon="@android:drawable/ic_menu_search"
        android:title="@string/search"
        app:actionViewClass="android.support.v7.widget.SearchView"
        app:showAsAction="collapseActionView|always" />
    <item
        android:id="@+id/action_checkbox"
        app:actionViewClass="android.widget.CheckBox"
        android:title="@string/filter"
        app:showAsAction="always" />
</menu>

2- You can use custom layout LINK