SearchView in expanded mode doesn't hide all a

2020-01-29 22:20发布

问题:

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: