0

I have following code :

val fragment = supportFragmentManager.findFragmentById(R.id.fragment_container)
                as SearchFragment? ?: searchFragment.also {
            addFragmentToActivity(it, R.id.fragment_container)

            search_view.setOnQueryTextListener(object : android.widget.SearchView.OnQueryTextListener {
                override fun onQueryTextSubmit(query: String): Boolean {
                    fragment.searchViewClicked(query)
                    return true
                }

                override fun onQueryTextChange(query: String): Boolean {
                    if (query.isEmpty()) {
                        fragment.clearList()
                    } else {
                        fragment.searchViewClicked(query)
                    }
                    return true
                }
            })

As you see I want to access fragment variable in onQueryTextSubmit and onQueryTextChange. But with current code I get unresolved reference error on fragment.

Could you let me know how should I fix the code?

Ali
  • 9,800
  • 19
  • 72
  • 152

3 Answers3

0

fragment is used within its assignment statement. i.e. fragment does not exist until the assignment is over. split the declaration/assignment and usage separately, that should fix the code.

Deepan
  • 124
  • 1
  • 10
0

Make a fragment object a class variable like this

private val fragment = FragmenLogin()

or use lateinit initialization

private lateinit var fragment: FragmentLogin

then you can use fragment object anywhere in the class (after it get initialized)

for more detail on lateinit see https://stackoverflow.com/a/36623703/5057663

naqi
  • 55
  • 8
0

Instead of :

val fragment = supportFragmentManager.findFragmentById(R.id.fragment_container)
                as SearchFragment? ?: searchFragment.also {
            addFragmentToActivity(it, R.id.fragment_container)
            ...
}

I should use :

val fragment = supportFragmentManager.findFragmentById(R.id.fragment_container)
                    as SearchFragment? ?: searchFragment.also {
                addFragmentToActivity(it, R.id.fragment_container)
             }
    ... // Continue of code
Ali
  • 9,800
  • 19
  • 72
  • 152