How to get menu options in actionbar aligned with fragments?

98 views Asked by At

On a tablet in landscape, the GMail app has the following:

screenshot of gmail app on tablet

The magnifying glass menu item appears to be aligned to the right side of the list fragment. How can I achieve this in my own app?

1

There are 1 answers

0
Mohit Khaitan On

Step I: Create a xml in the res/menu folder.

Step II: Add the following code snippet in the menu_main.xml or the pre-provided menu.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:yourapp="http://schemas.android.com/apk/res-auto" >
    <item android:id="@+id/action_search"
        android:title="@string/action_search"
        android:icon="@drawable/ic_action_search_hdpi"
        yourapp:showAsAction="always"
        android:enabled="true"
        yourapp:actionViewClass="android.support.v7.widget.SearchView" />
</menu>

` Step III: Inflate the menu.xml in the onCreateOptionsMenu(Menu menu)

 @Override
public boolean onCreateOptionsMenu(Menu menu) {

    super.onCreateOptionsMenu(menu);
    MenuInflater mi = getMenuInflater();
    mi.inflate(R.menu.menu_main, menu);

    return true;
}

Since Search is also a menu option, android already provides the widget to use it seamlessly.You can also handle a click listener to integrate the search mechanism into the app with the help of API's.

I hope it helps.