How to add toggle button in menu item in android

2019-03-10 22:02发布

问题:

I have options menu item in my application. Requirement was to add a toggle button to a menu item. Is this possible?

回答1:

UPDATE

You can use a custom layout in a menu item to add toggle button.

Create a layout with Switch (alternatively, you may also use ToggleButton), res/layout/menu_switch.xml:

<?xml version="1.0" encoding="utf-8"?>
<Switch xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:padding="64dp" />

And use that layout in menu item:

<?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">
    <item
        android:title="@string/switch_button_title"
        app:actionLayout="@layout/menu_switch"
        app:showAsAction="always" />
</menu>


You need to set android:checkable property of the menu to true and control its checked state in runtime. Example:

Menu:

<item
    android:id="@+id/checkable_menu"
    android:checkable="true"
    android:title="@string/checkable" />

Activity:

private boolean isChecked = false;

@Override
public boolean onPrepareOptionsMenu(Menu menu) {
    MenuItem checkable = menu.findItem(R.id.checkable_menu);
    checkable.setChecked(isChecked);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.checkable_menu:
            isChecked = !item.isChecked();
            item.setChecked(isChecked);
            return true;
        default:
            return false;
    }
}

Hope this helps.



回答2:

public boolean onPrepareOptionsMenu(final Menu menu) {       
      if(super.mMapView.isTraffic()) 
           menu.findItem(MENU_TRAFFIC_ID).setIcon(R.drawable.traffic_off_48); 
      else 
           menu.findItem(MENU_TRAFFIC_ID).setIcon(R.drawable.traffic_on_48); 

      return super.onPrepareOptionsMenu(menu); 
 }


回答3:

Do you mean you want to add a toggle button as one of the elements/items appearing in the options menu or add a button to a list item from the menu?

Then you can do it with a custom layout(use a ListView within if you want) and inflating it in the

public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.main_menu, menu);
    return true;
}

and you can save the values each time the button is toggles.

public boolean onOptionsItemSelected(MenuItem item) {
  switch (item.getItemId()) {
    case R.id.btnToggleValue:
      // save it here
      return true;
    case R.id.btnSecond:
      ...
      return true;
    default:
      return super.onOptionsItemSelected(item);
  }
}