Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to left align SearchView in AppCompat 21 with toolbar?

I want to left align the SearchView on tablets when using the new material theme and AppCompat 21. Is this possible or must I add my own custom layout to the toolbar?

enter image description here

  @Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_search, menu);
    mnuSearch = menu.findItem(R.id.menu_search);
    android.support.v7.widget.SearchView searchView = (SearchView) MenuItemCompat.getActionView(mnuSearch);
    searchView.setGravity(Gravity.LEFT);
    searchView.setIconifiedByDefault(false);
    searchView.setQueryHint(getString(R.string.search));
    searchView.requestFocus();
    return true;
}
like image 814
Christer Nordvik Avatar asked Jan 07 '15 09:01

Christer Nordvik


People also ask

How do I change the color of my SearchView icon?

Change the text colors and icons of searchview in action bar. Expand the search view by setting iconified and iconifiedByDefault flags to false. Find views inside the search view and set the colors as per your wish. Find views of the icons you wish to change and replace them with your icons.

What is SearchView?

android.widget.SearchView. A widget that provides a user interface for the user to enter a search query and submit a request to a search provider. Shows a list of query suggestions or results, if available, and allows the user to pick a suggestion or result to launch into.

How do I change the Search icon on the right side?

search_mag_icon); //Get parent of gathered icon ViewGroup linearLayoutSearchView = (ViewGroup) searchViewIcon. getParent(); //Remove it from the left... linearLayoutSearchView. removeView(searchViewIcon); //then put it back (to the right by default) linearLayoutSearchView.


1 Answers

I would rather define your SearchView in a layout and then call

View v = findViewById(R.id.your_search_view);
getSupportActionBar().setCustomView(v);

This way it comes already aligned on the left, and if it doesn't you can set its LayoutParams.

If you're using a Toolbar with AppCompat things are easier, because it acts as a ViewGroup.

<android.support.v7.widget.Toolbar
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:abc="http://schemas.android.com/apk/res-auto"
        android:id="@+id/toolbar"
        android:layout_height="?attr/actionBarSize"
        android:layout_width="match_parent">

    <your.SearchView />
        // here you have control over layout_gravity

</android.support.v7.widget.Toolbar>
like image 114
natario Avatar answered Oct 22 '22 01:10

natario