繁体   English   中英

如何将RelativeLayout添加为菜单项 - Android

[英]How to add a RelativeLayout as menu item - Android

我有一个带有itemgroup菜单的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"

因为如果您使用的是ActionbarSherlockAppCompat ,则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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM