Reputation: 881
Is there any better clean way to put a listener inside a Fragment?
class FooFragment : Fragment() {
companion object {
private lateinit var listener: (Int) -> Unit
fun newInstance(listener: (Int) -> Unit): FooFragment {
Companion.listener = listener
return FooFragment()
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_foo, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
btn.setOnClickListener {
listener(1234)
}
}
}
The call is so tidy...
FooFragment.newInstance {
// Do something
}
I know this code have problems due to maybe I lose the listener when the Fragment
is recreated and that the standard way is using the onAttach(context: Context?)
way.
But I want to create a new instance of the FooFragment
from other Fragment
(not an Activity
). I could use something like this:
private var listener: Listener? = null
interface Listener {
fun onFooClicked()
}
override fun onAttach(context: Context?) {
super.onAttach(context)
// listener = context as Listener
fragmentManager?.findFragmentById(R.id.fFooParent) as Listener
}
But this piece of code inside the onAttach(context: Context?)
method inside the FooFragment
, would be counterproductive due to I do not want that the FooFragment knows anything of the class who insntantiates it. Moreover, I would like that it could be a Fragment
or an Activity
.
Upvotes: 3
Views: 1493
Reputation: 37404
You can crate a baseActivity which implements the listener
class BaseFragmentActivity:AppCompatActivity(), FooFragment.Listener{}
then extend class YouFragmentActivity : BaseFragmentActivity
then it will make sure that every fragment hosting activity is equipped with container then you can get the reference as BaseFragmentActivity
You can replace AppCompatActivity
with BaseActivity
where BaseActivity :AppCompatActivity
Upvotes: 2