如何向android操作栏添加开关? [英] How to add a switch to android action bar?
问题描述
我想添加一个类似于 jellybean 原生外观的按钮开关.(视图顶部的蓝色/灰色开关)
I would like to add a button switch similar to jellybean native look. (Blue/gray switch at the top of the view)
文档显示了如何在那里创建菜单或添加图标,但没有说明如何添加自定义元素.例如.一个开关.http://developer.android.com/guide/topics/ui/actionbar.html
Documentation shows how to create a menu there or add icons, but it does not say, how to add a custom elements. eg. a switch. http://developer.android.com/guide/topics/ui/actionbar.html
推荐答案
为开关 switch_layout.xml
创建布局.菜单的自定义布局应始终为 RelativeLayout
Create a layout for the switch switch_layout.xml
. Custom layouts for menu should always be RelativeLayout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<Switch
android:id="@+id/switchForActionBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="" />
</RelativeLayout>
然后,在您的 mainmenu.xml
中添加如下项目
Then, in your mainmenu.xml
add the item as follows
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="@+id/myswitch"
android:title=""
android:showAsAction="always"
android:actionLayout="@layout/switch_layout"
/>
</menu>
在您的活动中,像往常一样对 mainmenu.xml
进行充气
And in your activity, inflate the mainmenu.xml
as you always do
getMenuInflater().inflate(R.menu.mainmenu, menu);
return true;
这篇关于如何向android操作栏添加开关?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!