In this app I tried to implement SearchView.OnQueryTextListener
in separate kotlin file like this
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
}
})
}
but when I tried to use it in fragment I can't see it in other methods, I see this error Interface OnQueryTextListener does not have constructors
the full code of fragment
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{ //
}
}
}
Name of your function OnQueryTextListener
seems to be conflicting with interface name SearchView.OnQueryTextListener
, so just use another name.
It is anyway recommended to start function names in lowercase, so changing the fun to eg. inline fun SearchView.onQueryTextListener(...)
should fix it.