Jay*_*Jay 4 android kotlin searchview
我收到“OnQueryTextListener 需要类型不匹配!” 尝试在导航片段中用 Kotlin 实现 searchview 时出错。我已经搜索了尽可能多的示例和 stackoverflow 问题,一切都表明我的代码应该是正确的。请注意,我的搜索视图是持久的(不是菜单的一部分),因此我无法执行 menu.finditem。
这是我的 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
}
})
}
Run Code Online (Sandbox Code Playgroud)
和布局代码:
<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"
/>
Run Code Online (Sandbox Code Playgroud)
有两个SearchView小部件:
android.widget.SearchViewandroidx.appcompat.widget.SearchView它们扮演相同的角色,但不兼容,并且它们的嵌套接口(例如 )OnQueryTextListener也不兼容。
确保在资源(例如布局)和任何import语句中使用相同的资源。如果您使用 AppCompat,您可能需要androidx.appcompat.widget.SearchView.
| 归档时间: |
|
| 查看次数: |
2371 次 |
| 最近记录: |