Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Center SearchView in Action Bar

How can I center an ActionView (a SearchView in particular) inside of a Action Bar?

As seen in the Google Books app:

  Google Books app SearchView

My current layout setup (search_layout.xml):

<?xml version="1.0" encoding="utf-8"?>
<SearchView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:queryHint="@string/search_hint" />

My Action Bar XML file (menu.xml):

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:icon="@+android:drawable/ic_menu_search"
        android:title="@string/search"
        android:showAsAction="always|collapseActionView"
        android:id="@+id/searchMenuItem"
        android:actionLayout="@layout/search_layout" />
</menu>

Is there a way to mimic the behaviour of the Books' SearchView?

like image 960
Whymarrh Avatar asked Dec 07 '12 08:12

Whymarrh


1 Answers

A View centered in the ActionBar can't be achieved with Action Items in an xml menu, as far as I can tell. However it can be implemented by setting a custom layout to the ActionBar. A basic example:

An Activity:

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ActionBar actionBar = getActionBar();
        actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM); 
        actionBar.setDisplayShowHomeEnabled(true);
        actionBar.setCustomView(R.layout.actionbar_layout);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

}

where actionbar_layout is:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <SearchView
        android:id="@+id/mySearchView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:iconifiedByDefault="false" />
</RelativeLayout>

creates this on a 7'' tablet:

enter image description here

Note the iconifiedByDefault attribute set to false on the SearchView which forces it to appear expanded and not just as an icon. This may require that you hide the softkeyboard programmatically or it will be launched open when the Activity starts.

like image 184
onosendai Avatar answered Oct 18 '22 10:10

onosendai