SearchView taking all the space in the new ActionBarCompat

不问归期 提交于 2019-11-28 07:33:42

This is definitely a bug about Android but a workaround can be including SearchView programmatically like this:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    SearchView searchView = new SearchView(getSupportActionBar().getThemedContext());
    searchView.setIconifiedByDefault(false);
    getActionBar().setCustomView(searchView);
    getActionBar().setDisplayShowCustomEnabled(true);
}

You can also use a layout XML to define SearchView properties. However "iconifiedByDefault" in XML tends to be ineffective in my experience. (This may my bad though)

Thanks for creating an issue about this. Here's the URL to the related bug report: https://code.google.com/p/android/issues/detail?id=58251

Despite what is mentioned in the bug report, my experience was the same with both ActionBarSherlock and ActionBarCompat. So I expect that ActionBarSherlock users are also affected.

Have you tried using collapseActionView()?

I use it like this:

public static MenuItem msearchMenuItem;

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);

    // Associate searchable configuration with the SearchView
    SearchManager searchManager =
           (SearchManager) getSystemService(Context.SEARCH_SERVICE);
    SearchView searchView =
            (SearchView) menu.findItem(R.id.search).getActionView();

    searchView.setSearchableInfo(
            searchManager.getSearchableInfo(getComponentName()));



    msearchMenuItem = menu.findItem(R.id.search);

    return true;
}
public static MenuItem getSearchMenuItem() {
    return msearchMenuItem;
}

public void doSomething(){
    //Collapse the SearchBar
    getSearchMenuItem().collapseActionView();
}

I don't know if it works with v7, but it certainly works with v4.

Try changing android:showAsAction="collapseActionView|ifRoom"

<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/search"
      android:title="@string/search_title"
      android:icon="@drawable/ic_search"
      android:showAsAction="collapseActionView|ifRoom"
      android:actionViewClass="android.widget.SearchView" />
</menu>

Remove the line

searchView.setIconifiedByDefault(false);

Or you can explicitly call the method with true as the argument.

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