androidgeneric-programmingabstractionandroid-viewbinding

How to use abstraction with ViewBinding with base activity?


I was making a base class so that all bindings for child will be set in base

I have done till this

abstract class BaseActivity2<B : ViewBinding?, T : BaseViewModel?> : AppCompatActivity() {
    private var viewBinding: B? = null
    private var baseViewModel: T? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }
}

but am unable to get a way to bind view in oncreat() generally we bind layout in view binding as

binding = ActivityLoginBinding.inflate(layoutInflater)
        setContentView(binding.root)

but i am looking for generalized way in base activity


Solution

  • Other answer will also solve problem but I would like to do in a clean way.

    My Base Class

    abstract class BaseVMActivity<VM : ViewModel, B : ViewBinding> : BaseActivity() {
    
        lateinit var viewModel: VM
        lateinit var binding: B
    
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            viewModel = ViewModelProvider(this, factory).get(getViewModelClass())
            binding = getViewBinding()
            setContentView(binding.root)
        }
    
        private fun getViewModelClass(): Class<VM> {
            val type = (javaClass.genericSuperclass as ParameterizedType).actualTypeArguments[0]
            return type as Class<VM>
        }
    
        abstract fun getViewBinding(): B
    
    }
    

    My activity:

    class MainActivity : BaseVMActivity<AppViewModel, ActivityMainBinding>() {
        override fun getViewBinding() = ActivityMainBinding.inflate(layoutInflater)
       
    }
    

    Now I can directly access viewModel or binding:

    fun dummy(){
            binding.bvReport.text = viewModel.getReportText()
        }