将SearchView添加到片段中的自定义工具栏



我正在尝试将SearchView添加到我的自定义工具栏中。我曾尝试使用toolbar.addView(searchView)将SearchView直接添加到工具栏中,但它没有改变任何内容,无论我尝试什么,我都会得到一个空白的工具栏。我做错了什么?这应该很简单。。。

工具栏:

<?xml version="1.0" encoding="utf-8"?>
<androidx.appcompat.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:elevation="4dp"
android:theme="@style/ThemeOverlay.AppCompat.Light"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light">
</androidx.appcompat.widget.Toolbar>

搜索菜单:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/action_search"
android:icon="@drawable/ic_search"
android:title="Search"
app:actionViewClass="androidx.appcompat.widget.SearchView"
app:showAsAction="ifRoom|collapseActionView" />
</menu>

片段:

lateinit var toolbar: Toolbar
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
view = ConstraintLayout(this.context)
view.layoutParams = ConstraintLayout.LayoutParams(ConstraintLayout.LayoutParams.MATCH_PARENT, ConstraintLayout.LayoutParams.MATCH_PARENT)
toolbar = inflater.inflate(R.layout.toolbar, container, false) as Toolbar
setHasOptionsMenu(true)
return view
}

override fun onCreateOptionsMenu(menu: Menu?, inflater: MenuInflater?) {
super.onCreateOptionsMenu(menu, inflater)
// Inflate the options menu from XML
inflater?.inflate(R.menu.search_menu, menu)
val searchItem = menu?.findItem(R.id.action_search)
val searchView = searchItem?.actionView as SearchView
searchView.imeOptions = EditorInfo.IME_ACTION_DONE
searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
override fun onQueryTextSubmit(p0: String?): Boolean {
return false
}
override fun onQueryTextChange(p0: String?): Boolean {
//adapter.getFilter().filter(newText);
return false
}
})
toolbar.addView(searchView)
}

在onCreateView((中添加setSupportActionBar(toolbar)解决了问题

相关内容

  • 没有找到相关文章

最新更新