Center SearchView in Action Bar

五迷三道 提交于 2019-11-29 11:56:00

问题


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

As seen in the Google Books app:

  

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?


回答1:


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:

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.




回答2:


Have a look here. You can just use the android:actionViewClass="android.widget.SearchView" attribute, and that should work just fine (keep in mind that you can get a reference to the searchView in Java, and change the hint there if that's what you want).



来源:https://stackoverflow.com/questions/13759148/center-searchview-in-action-bar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!