Kotlin导航片段中的searchview.setonquerytextlistener()类型不匹配

问题描述 投票:1回答:1

我收到“需要类型不匹配的OnQueryTextListener!”尝试在导航片段的Kotlin中实现searchview时发生错误。我已经搜索了尽可能多的示例和stackoverflow问题,所有内容都表明我的代码应该正确。请注意,我的搜索视图是持久的(不是菜单的一部分),因此无法执行menu.finditem。

enter image description here

这是我的HomeFragment代码:

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
        }
    })
}

和布局代码:

<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"
    />

android kotlin searchview
1个回答
0
投票

有两个SearchView小部件:

  • android.widget.SearchView
  • androidx.appcompat.widget.SearchView

这些角色扮演相同角色,但不兼容,并且它们的嵌套接口,例如OnQueryTextListener,也不兼容。

请确保在资源(例如布局)和任何import语句中都使用相同的内容。如果您使用的是AppCompat,则可能需要androidx.appcompat.widget.SearchView

© www.soinside.com 2019 - 2024. All rights reserved.