SearchView in expanded mode doesn't hide all action bar icons starting from Marshmallow

喜你入骨 提交于 2019-11-26 18:43:28

问题


SearchView looks fine on Lollipop devices (Android 21):

But on Android 23-28 it doesn't hide all icons on the right side:

<item android:id="@+id/action_search"
      android:title="@string/search"
      app:actionViewClass="androidx.appcompat.widget.SearchView"
      app:showAsAction="ifRoom"/>

<item android:id="@+id/action_sort"
      android:title="@string/sorting"
      android:icon="@drawable/sort"
      app:showAsAction="ifRoom"/>

How can I fix it?

Update

Seems Android 23 and higher don't hide icons anymore on the right (because there is enough space)

But it only works fine if you don't have home button or hamburger menu on the left:

But I have an icon on the left and that's why my action bar looks ugly when SearchView is expanded:

Should be a bug in newest Android ActionBar design...

I add menu button like this:

supportActionBar?.let {
    it.setDisplayHomeAsUpEnabled(true)
    it.setHomeAsUpIndicator(R.drawable.ic_menu)
}

回答1:


My solution is to hide the button on the left (home/menu) programmatically when SearchView is expanded:

val searchItem = menu.findItem(R.id.action_search)

val searchView = searchItem.actionView as SearchView

searchView?.setOnSearchClickListener {
    supportActionBar?.setDisplayHomeAsUpEnabled(false)
}
searchView?.setOnCloseListener {
    supportActionBar?.setDisplayHomeAsUpEnabled(true)
    false
}

p.s. the next method didn't work for me because it works only if your SearchView is always expanded (marked as collapseActionView) but I don't want such weird thing in my app (it's not a search app, search function is just an additional feature):

searchItem.setOnActionExpandListener(object: MenuItem.OnActionExpandListener {
    override fun onMenuItemActionExpand(item: MenuItem?): Boolean {
        supportActionBar?.setDisplayHomeAsUpEnabled(false)
        return true
    }

    override fun onMenuItemActionCollapse(item: MenuItem?): Boolean {
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        return true
    }
})

Closed:

Expanded:



来源:https://stackoverflow.com/questions/56410048/searchview-in-expanded-mode-doesnt-hide-all-action-bar-icons-starting-from-mars

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