Для справки
Это ветвь, показывающая проблему ( обратите внимание, что проект не завершен ). Запустите его, и вы увидите ошибку времени компиляции Unresolved reference: search_src_text
.
https://github.com/mitchtabian/Clean-Notes/blob/searchview-issue/notes/src/main/java/com/codingwithmitch/cleannotes/notes/framework/presentation/notelist/NoteListFragment.kt
Что я пытаюсь сделать:
Я хочу отправить текст в мою ViewModel из SearchView. Когда текст отправлен, я выполняю запрос, используя этот текст.
Что вы можете подумать:
«Просто используйте OnQueryTextListener
.»
OnQueryTextListener
не будет отправлять текст, если текст пуст / пуст. Я использую нулевой / пустой регистр для поиска всего в базе данных. Так что это не работает.
Обходное решение, которое я пробовал:
В прошлом я вручную искал идентификатор представления SearchAutoComplete
внутри SearchView. Вы можете найти это следующим образом:
val searchPlate: SearchView.SearchAutoComplete? = search_view.findViewById(R.id.search_src_text)
Затем вы просто присоединяете OnEditorActionListener
и слушаете действия IME, и вы хороши для go:
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
}
Обычно это отлично работает Единственное отличие (которое я вижу) состоит в том, что в этот раз я использую Dynami c Feature Module . При попытке доступа к R.id.search_src_text
выдается следующее сообщение об ошибке компиляции:
Unresolved reference: search_src_text
И да, макет находится в каталоге динамического c функционального модуля / 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
.
Еще одна странная вещь:
I перебирал иерархию 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
}
}
}
}
}
}
}
Любые идеи будут высоко оценены.