shubhamsingh
shubhamsingh

Reputation: 402

How to add a RelativeLayout as menu item - Android

I have an XML for menu with an item and a group. I intend to add a RelativeLayout as a menu item in the XML, so that it looks like:

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

Can this be accomplish in the Layout XML, or programmatically? If not, a work around would be helpful. Thanks.

Upvotes: 3

Views: 2650

Answers (3)

Imdad
Imdad

Reputation: 693

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

Upvotes: 4

Harshad Pansuriya
Harshad Pansuriya

Reputation: 20950

Important Point :

To use Relativelayout or any Other Layout you have to use actionLayout as @Jack's retarded code Answer. But Keep in mind that.

android:actionLayout="@layout/my_custom_layout" is not work you have to use app:actionLayout="@layout/my_custom_layout"

Because If you're using ActionbarSherlock or AppCompat, the android: namespace will not work for 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.

Upvotes: 3

Miguel Fermin
Miguel Fermin

Reputation: 380

You can't put it in the menu.xml directly, you have to use the android:actionLayout attribute.

It works like this:

menu.xml

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

custom_layout.xml

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

Upvotes: 0

Related Questions