Salman khan
Salman khan

Reputation: 1265

View between menu items in toolbar

Is it possible to take view in menu items of toolbar?

I want view like shown in yellow color between two menu items of toolbar.

Upvotes: 3

Views: 555

Answers (2)

Kapil Rajput
Kapil Rajput

Reputation: 11565

Simply create a divider line view in xml file to show a divider line.

dividerLine.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<View
android:layout_width="1dp"
android:layout_height="?android:attr/actionBarSize" 
android:background="@android:color/darker_gray"/> 
 </LinearLayout>

and set actionLayout to an item in menu xml to show divider line

activity_menu.xml

 <menu xmlns:android="http://schemas.android.com/apk/res/android" >

<item android:id="@+id/your_icon1"
      android:icon="@drawable/image1"
      android:title="@string/text1"
      app:showAsAction="always"
      />

<item android:id="@+id/icon2TricktoShowDividerLine"
     android:actionLayout="@layout/dividerLine" 
     app:showAsAction="always"
     android:title="@string/text2" />

<item android:id="@+id/your_icon3"
      android:icon="@drawable/icon"
      android:title="@string/text3"
      app:showAsAction="always" />
 </menu>

android:actionLayout="@layout/dividerLine" shows divider line between menu items. Hope this helps you.

Updated

I am getting this type of view from my above code :

enter image description here

Upvotes: 1

Mustansar Saeed
Mustansar Saeed

Reputation: 2790

You have to create the custom layout for menuItem uing actionLayout and then in oncreateOptionsMenue get the menuItem view and change your image view icon to vertical drawable

layout_actionitem.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent">
    <ImageView
        android:id="@+id/actionItemImage"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginLeft="1dp"/>

</LinearLayout>

Your menu xml

<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@+id/item_save"
        android:icon="@drawable/exit"
        android:showAsAction="always"
        android:actionLayout="@layout/layout_actionitem"
        android:title=""/>
</menu>

onCreateOptionsMenu

@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        LinearLayout actionItemLayout = (LinearLayout) menu.findItem(R.id.item_save).getActionView();
        ImageView iv = (ImageView)actionItemLayout.findViewById(R.id.actionItemImage);
        iv.setBackgroundDrawable(getResources().getDrawable(R.drawable.icon_save));
}

Hope this helps.

Upvotes: 0

Related Questions