这是显示问题的分支(注意项目未完成)。运行它,您将看到编译时错误Unresolved reference: search_src_text
。
我想从SearchView向我的ViewModel提交文本。提交文本后,我将使用该文本执行查询。
“只需使用
OnQueryTextListener
。”
OnQueryTextListener
将不会提交文本,如果文本为空/空。我正在使用null / empty情况来搜索数据库中的所有内容。所以那行不通。
过去,我已经在SearchView中手动搜索了SearchAutoComplete
视图的ID。您可以这样找到它:
val searchPlate: SearchView.SearchAutoComplete? = search_view.findViewById(R.id.search_src_text)
然后您只需附加一个OnEditorActionListener
并监听IME动作,您就可以开始了:
searchPlate.setOnEditorActionListener { v, actionId, event ->
if (actionId == EditorInfo.IME_ACTION_UNSPECIFIED
|| actionId == EditorInfo.IME_ACTION_SEARCH ) {
val searchQuery = v.text.toString()
viewModel.setQuery(searchQuery)
viewmodel.executeSearch()
}
true
}
通常,这很好。唯一的区别(我可以看到)是这次使用的是动态功能模块。尝试访问R.id.search_src_text
时会引发此编译时错误:
Unresolved reference: search_src_text
是,布局在动态要素模块的/ res /目录中。
1。布局中的SearchView
<androidx.constraintlayout.widget.ConstraintLayout
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="match_parent"
android:background="@color/app_background_color"
>
<androidx.appcompat.widget.SearchView
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:iconifiedByDefault="false"
android:queryHint="@string/text_Search"
android:layout_centerHorizontal="true" />
</androidx.constraintlayout.widget.ConstraintLayout>
2。获取对search_src_text的引用
val searchPlate: SearchView.SearchAutoComplete? = search_view.findViewById(R.id.search_src_text)
运行项目将产生错误Unresolved reference: search_src_text
。
我遍历了View层次结构,直到找到SearchAutoComplete,然后附加了侦听器,效果很好...
for((index1, child) in search_view.children.withIndex()){
printLogD("ListFragment", "${index1}, ${child}")
for((index2, child2) in (child as ViewGroup).children.withIndex()){
printLogD("ListFragment", "T2: ${index2}, ${child2}")
if(child2 is ViewGroup){
for((index3, child3) in (child2 as ViewGroup).children.withIndex()){
printLogD("ListFragment", "T3: ${index3}, ${child3}")
if(child3 is ViewGroup){
for((index4, child4) in (child3 as ViewGroup).children.withIndex()){
printLogD("ListFragment", "T4: ${index4}, ${child4}")
if(child4 is SearchView.SearchAutoComplete){
child4.setOnEditorActionListener { v, actionId, event ->
if (actionId == EditorInfo.IME_ACTION_UNSPECIFIED
|| actionId == EditorInfo.IME_ACTION_SEARCH ) {
val searchQuery = v.text.toString()
printLogD("NoteList", "SearchView: (keyboard or arrow) executing search...: ${searchQuery}")
viewModel.setQuery(searchQuery).let{
viewModel.loadFirstPage()
}
}
true
}
break
}
}
}
}
}
}
}
任何见解将不胜感激。
val searchPlate:SearchView.SearchAutoComplete? = search_view.findViewById(androidx.appcompat.R.id.search_src_text)