以供参考
这是一个显示问题的分支(注意项目不完整)。运行它,你会看到编译时错误Unresolved reference: search_src_text
。
我正在尝试做的事情:
我想从 SearchView 向我的 ViewModel 提交文本。提交文本后,我使用该文本执行查询。
你可能在想什么:
“就用一个
OnQueryTextListener
。”
如果OnQueryTextListener
文本为空/空,则不会提交文本。我正在使用 null/empty case 来搜索数据库中的所有内容。所以这行不通。
我尝试的解决方法:
过去,我SearchAutoComplete
在 SearchView 中手动搜索了视图的 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
}
通常这工作正常。唯一的区别(我可以看到)是这次我使用的是Dynamic Feature Module。尝试访问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
。
另一个奇怪的事情:
我遍历视图层次结构,直到找到 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
}
}
}
}
}
}
}
任何见解将不胜感激。