androidandroid-activityviewonclickfragment

How to have multiple views in fragment call the same onClick function declared in the fragment class?


I have about 8 different buttons in a fragment, which all should call the same function. I set their tag property in xml to call that function. I declared that function in the fragment class, but upon calling it, the app crashes with an error java.lang.IllegalStateException: Could not find method onTaskButtonClick(View) in a parent or ancestor Context for android:onClick attribute defined on view class androidx.appcompat.widget.AppCompatButton with id 'btn_playpause'

I found out that I would have to implement that function in the Activity that hosts the fragment. I would however like to avoid that because the Activity will host potentially 5+ fragments and if all fragment functions are implemented in that one Activity it will get way too large for my liking.

edit

Basically, I want to avoid this:

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    btn_playpause.setOnClickListener { onTaskButtonClick(view) }
    btn_previous_track.setOnClickListener { onTaskButtonClick(view) }
    btn_next_track.setOnClickListener { onTaskButtonClick(view) }
    btn_volume_down.setOnClickListener { onTaskButtonClick(view) }
    btn_volume_up.setOnClickListener { onTaskButtonClick(view) }
    btn_mute.setOnClickListener { onTaskButtonClick(view) }
}

fun onTaskButtonClick(view: View) {
    presenter.onTaskButtonPressed(view.tag.toString())
}

It would seem easier it seems to just have the buttons point to that function in xml.


Solution

  • You can use vararg.

     override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        setClickListenerOnViews(
            btn_playpause,
            btn_previous_track,
            btn_next_track,
            btn_volume_down,
            btn_volume_up,
            btn_mute
        )
    }
    
    private fun setClickListenerOnViews(vararg views: View) {
        views.forEach {
            it.setOnClickListener { presenter.onTaskButtonPressed(it.tag.toString()) }
        }
    }