Home > Net >  Kotlin Android Navigation to Fragment don't work in setOnItemClickListener
Kotlin Android Navigation to Fragment don't work in setOnItemClickListener

Time:10-13

I am in a fragment with listview and a working onItemClickListener.

When I test the onItemClickListener e.g. by showing a toast everything works.

This is how my file looks like:

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        with (binding) {
            val arrayAdapter: ArrayAdapter<*>
            val employeeCategories = arrayOf(
                "Test", "Test2", "Test3"
            )

            arrayAdapter = ArrayAdapter(
                activity!!,
                android.R.layout.simple_list_item_1, employeeCategories)

            employeeListView.apply {
                adapter = arrayAdapter
            }


            employeeListView.setOnItemClickListener{parent, view, position, id ->
                if (position==0){
                    Toast.makeText(activity, "Item One",   Toast.LENGTH_SHORT).show()
                }
                
            }
        }
    }

To navigate from this fragment to another, I want to do the following when a List Item is clicked:

            activity!!.findNavController(R.id.nav_host_fragment).popBackStack()
            activity!!.findNavController(R.id.nav_host_fragment).navigate(R.id.navigation_help)

If I add this outside the onItemClickListener, it also navigates successfully. However, if I add the same in the onItemClickListener, at the place where the toast was before for testing, it does not work anymore. There is no navigation after I have clicked on an item:


            activity!!.findNavController(R.id.nav_host_fragment).popBackStack()
            activity!!.findNavController(R.id.nav_host_fragment).navigate(R.id.navigation_help)  <---- WORKS!

            employeeListView.setOnItemClickListener{parent, view, position, id ->
                if (position==0){
                    activity!!.findNavController(R.id.nav_host_fragment).popBackStack()
                    activity!!.findNavController(R.id.nav_host_fragment).navigate(R.id.navigation_help)  <---- DONT WORKS! :(              
                }

I am still relatively new to Kotlin and unfortunately cannot explain why this works outside of the onItemClickListener but not in combination with it. Can someone possibly tell me what this could be related to?

CodePudding user response:

Can you add as a global variable (outside of your onViewCreated method) the following:

private val navController by lazy { findNavController() }

and afterwards do the this:

employeeListView.setOnItemClickListener{parent, view, position, id ->
                if (position==0){
                   navController.popBackStack()
                   navController.navigate(R.id.navigation_help)
                }

and let me know if it works now?

  • Related