簡體   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