无法从 onCreateOptionsMenu 调用内联乐趣 SearchView.OnQueryTextListener

Cannot call inline fun SearchView.OnQueryTextListener from onCreateOptionsMenu

在这个应用程序中,我尝试像这样在单独的 kotlin 文件中实现 SearchView.OnQueryTextListener

import androidx.appcompat.widget.SearchView

inline fun SearchView.OnQueryTextListener(crossinline listener: (String) -> Unit) {
    this.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
        override fun onQueryTextSubmit(query: String?): Boolean {
            return true
        }

        override fun onQueryTextChange(newText: String?): Boolean {
            listener(newText.orEmpty())
            return true
        }

    })

}

但是当我尝试在片段中使用它时我无法在其他方法中看到它,我看到了这个错误 Interface OnQueryTextListener does not have constructors

片段完整代码

AndroidEntryPoint
class TasksFragment : Fragment(R.layout.fragment_tasks) {

    private val tasksViewModel: TasksViewModel by viewModels()
    private var binding: FragmentTasksBinding?=null

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {

        binding = FragmentTasksBinding.inflate(inflater, container, false)

        val tasksAdapter:TasksAdapter = TasksAdapter()

        binding?.apply {
            recyclerViewTasks.apply {
                adapter = tasksAdapter
                layoutManager = LinearLayoutManager(requireContext())
                setHasFixedSize(true)

            }
        }

        tasksViewModel.task.observe(viewLifecycleOwner, {
            tasksAdapter.submitList(it)
        })

        return binding!!.root
    }

    override fun onDestroyView() {
        super.onDestroyView()
        binding = null
    }

    override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
        inflater.inflate(R.menu.menu_fragment_tasks,menu)

        val searchItem = menu.findItem(R.id.action_search)
        val searchView = searchItem.actionView as SearchView

        searchView.OnQueryTextListener{ //

        }


    }


}

您的函数名称 OnQueryTextListener 似乎与接口名称 SearchView.OnQueryTextListener 冲突,所以请使用其他名称。

无论如何recommended 函数名以小写开头,所以将 fun 改为 eg。 inline fun SearchView.onQueryTextListener(...) 应该修复它。