Create a Base Activity with ViewBinding for multiple activities with same views

188 views Asked by At

i have twenty different activities with the same MaterialTextView (same name in all activities)

in all activities (in the onCreate event), i initialize the textview with the same text:

textview.text = "Hello"

each activity has a different binding XML, like ActivityOneBinding, ActivityTwoBinding, ActivitythreeBinding, and so on

i need to reduce the "repeated code" in all activites with the creation of an actract class to inherit, and set the text in there one time

I have tried examples of abstract class to inherit, but the name of the textview does not recognize because they are different bindings

1

There are 1 answers

0
Marcin Mrugas On BEST ANSWER

I have tried examples of abstract class to inherit, but the name of the textview does not recognize because they are different bindings

Instead of passing view name, you can pass reference to TextView object. In this example such function is getHeaderView():

BaseActivity.kt

abstract class BaseActivity<VB : ViewBinding>() : AppCompatActivity() {
    abstract fun getHeaderView(): TextView

    protected lateinit var  binding: VB

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = inflateView()
        setContentView(binding.root)
    }

    override fun onPostCreate(savedInstanceState: Bundle?) {
        super.onPostCreate(savedInstanceState)
        val headerView = getHeaderView()
        headerView.text = "Hello world!"
    }

    abstract fun inflateView(): VB
}
class SecondActivity : BaseActivity<SecondActivityBinding>() {

    override fun getHeaderView(): TextView = binding.headerView

    override fun inflateView() = SecondActivityBinding.inflate(layoutInflater)
}