ViewBinding abstract class or interface

Viewed 578

Is there any way to make an abstract class or interface for ViewBinding. Maybe I will show a simple example of what I exactly mean.

Let's say that I have two fragments. Both have TextView named universalTextView. In fragment classes I have value someText = "Text". I want to set this value to universalTextView. Now in both fragments, I have the same code so I made an abstract class, to reduce boilerplate code, that holds someText and set text for universalTextView. It looks like this:

abstract class AbstractFragment(
    @LayoutRes layout: Int
) : Fragment(layout)
{
    protected abstract val binding: ViewBinding
    protected val someText = "Text"

    override fun onViewCreated(view: View, savedInstanceState: Bundle?)
    {
        super.onViewCreated(view, savedInstanceState)
        binding.root.findViewById<TextView>(R.id.universalTextView).text = someText
    }
}

But with this approach, I am losing the biggest advantage of ViewBinding and I have to use findViewById. Is there any way to make an abstract class for ViewBinding, something like this:

abstract class AbstractViewBinding : ViewBinding
{
    abstract val universalTextView : TextView
}

So in AbstractFragment I can use protected abstract val binding: AbstractViewBinding and change text without using findViewById. But now, somehow I have to tell the app that ViewBinding used in every fragment that extends AbstractFragment will have universalTextView. Is this even possible?

1 Answers

I don't think this is directly possible, there isn't any sort of inheritance mechanism in view binding. Instead you could have a structure like this:

abstract class AbstractFragment : Fragment {

    abstract val universalTextView: TextView
    protected val someText = "Text"

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {

        super.onViewCreated(view, savedInstanceState)
        universalTextView.text = someText
    }
}
class Fragment1 : AbstractFragment {
  
    lateinit var binding: Fragment1Binding
    override val universalTextView
        get() = binding.utv
}

but I realise this isn't quite what you wanted.

Related