如何在android的菜单项中添加切换按钮 [英] How to add toggle button in menu item in android
本文介绍了如何在android的菜单项中添加切换按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
I have options menu item in my application. Requirement was to add a toggle button to a menu item. Is this possible?
解决方案
As of this writing there are 3 options.
1) Use app:actionViewClass
. Example:
<?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="Switch!"
app:actionViewClass="android.widget.Switch"
app:showAsAction="always" />
</menu>
2) You can use a custom layout in a menu item to add toggle button. Example:
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>
3) 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.
这篇关于如何在android的菜单项中添加切换按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文