I'm getting a "type mismatch required OnQueryTextListener!" error when trying to implement searchview in Kotlin in a Navigation Fragment. I've searched as many samples and stackoverflow questions as I could and everything says my code should be correct. Note that my searchview is PERSISTANT (not part of the menu), so I cannot do a menu.finditem.
Here is my HomeFragment code :
class HomeFragment : Fragment() {
private lateinit var homeViewModel: HomeViewModel
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_home, container, false)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
println("***************** Home Fragment *******************")
searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
override fun onQueryTextSubmit(query: String): Boolean {
// task HERE
return false
}
override fun onQueryTextChange(newText: String): Boolean {
return false
}
})
}
and the layout code:
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/materialBackgroundGrey">
<androidx.cardview.widget.CardView
android:id="@+id/cardView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:iconifiedByDefault="false"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:queryBackground="@null">
<SearchView
android:id="@+id/searchView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:queryHint="Search"
app:iconifiedByDefault="false"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.cardview.widget.CardView>
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:background="@color/colorWhite"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/cardView"
app:layout_constraintBottom_toBottomOf="parent"
/>
There are two SearchView
widgets:
android.widget.SearchView
androidx.appcompat.widget.SearchView
These fill the same role but are not compatible, and their nested interfaces, like OnQueryTextListener
, are not compatible.
Make sure that you use the same one both in resources (such as your layout) and in any import
statements. If you are using AppCompat, you probably want androidx.appcompat.widget.SearchView
.