简体   繁体   English

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

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

I have an XML for menu with an item and a group . 我有一个带有itemgroup菜单的XML。 I intend to add a RelativeLayout as a menu item in the XML, so that it looks like: 我打算在XML中添加一个RelativeLayout作为菜单项,所以它看起来像:

<menu>
    <item1/>
    <item2
         <RelativeLayout>
               <TextView1/>
               <TextView2/>
         <RelativeLayout>
    />
</menu>

Can this be accomplish in the Layout XML, or programmatically? 这可以在Layout XML中完成,还是以编程方式完成? If not, a work around would be helpful. 如果没有,解决方案会有所帮助。 Thanks. 谢谢。

Create a layout file with a view you want and then use it like this - 使用您想要的视图创建布局文件,然后像这样使用它 -

<item
    android:id="@+id/menu_refresh"
    android:title="@string/refresh"
    yourapp:showAsAction="never"
    android:actionLayout="@layout/my_custom_layout"/>

To edit your text view - 要编辑文本视图 -

@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;
}

Important Point : 很重要的一点 :

To use Relativelayout or any Other Layout you have to use actionLayout as @Jack's retarded code Answer. 要使用Relativelayout或任何其他布局,您必须使用actionLayout作为@ Jack的延迟代码答案。 But Keep in mind that. 但请记住。

android:actionLayout="@layout/my_custom_layout" is not work you have to use app:actionLayout="@layout/my_custom_layout" android:actionLayout="@layout/my_custom_layout"不起作用你必须使用app:actionLayout="@layout/my_custom_layout"

Because If you're using ActionbarSherlock or AppCompat , the android: namespace will not work for MenuItems . 因为如果您使用的是ActionbarSherlockAppCompat ,则android:命名空间将不适用于MenuItems This is because these libraries use custom attributes that mimic the Android APIs since they did not exist in earlier versions of the framework. 这是因为这些库使用模仿Android API的自定义属性,因为它们在早期版本的框架中不存在。

You can't put it in the menu.xml directly, you have to use the android:actionLayout attribute. 你不能直接把它放在menu.xml中,你必须使用android:actionLayout属性。

It works like this: 它的工作原理如下:

menu.xml menu.xml文件

<menu>
    <item ... android:actionLayout="@layout/custom_layout"/>
</menu>

custom_layout.xml custom_layout.xml

<RelativeLayout ...>
    <TextView .../>
    <TextView .../>
<RelativeLayout>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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