[英]How to add a RelativeLayout as menu item - Android
我有一个带有item
和group
菜单的XML。 我打算在XML中添加一个RelativeLayout
作为菜单项,所以它看起来像:
<menu>
<item1/>
<item2
<RelativeLayout>
<TextView1/>
<TextView2/>
<RelativeLayout>
/>
</menu>
这可以在Layout XML中完成,还是以编程方式完成? 如果没有,解决方案会有所帮助。 谢谢。
使用您想要的视图创建布局文件,然后像这样使用它 -
<item
android:id="@+id/menu_refresh"
android:title="@string/refresh"
yourapp:showAsAction="never"
android:actionLayout="@layout/my_custom_layout"/>
要编辑文本视图 -
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
//Get a reference to your item by id
MenuItem item = menu.findItem(R.id.menu_refresh);
//Here, you get access to the view of your item, in this case, the layout of the item has a RelativeLayout as root view but you can change it to whatever you use
RelativeLayout rootView = (RelativeLayout)item.getActionView();
//Then you access to your control by finding it in the rootView
TextView textview1 = (TextView) rootView.findViewById(R.id.text1);
//And from here you can do whatever you want with your text view
return true;
}
要使用Relativelayout
或任何其他布局,您必须使用actionLayout
作为@ Jack的延迟代码答案。 但请记住。
android:actionLayout="@layout/my_custom_layout"
不起作用你必须使用app:actionLayout="@layout/my_custom_layout"
因为如果您使用的是ActionbarSherlock
或AppCompat
,则android:
命名空间将不适用于MenuItems
。 这是因为这些库使用模仿Android API的自定义属性,因为它们在早期版本的框架中不存在。
你不能直接把它放在menu.xml中,你必须使用android:actionLayout属性。
它的工作原理如下:
menu.xml文件
<menu>
<item ... android:actionLayout="@layout/custom_layout"/>
</menu>
custom_layout.xml
<RelativeLayout ...>
<TextView .../>
<TextView .../>
<RelativeLayout>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.