Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 733
Mirza Ahmed Baig Avatar asked Sep 01 '20 10:09

Mirza Ahmed Baig


People also ask

What is view binding in Android?

View binding is a feature that allows you to more easily write code that interacts with views. Once view binding is enabled in a module, it generates a binding class for each XML layout file present in that module.


Video Answer


2 Answers

You can declare a lambda property in the constructor to create the binding object

abstract class BaseActivity<B : ViewBinding>(val bindingFactory: (LayoutInflater) -> B) : AppCompatActivity() {
    private lateinit var binding: B

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

You can also define binding as lazy property

private val binding: B by lazy { bindingFactory(layoutInflater) }

Then you need to override nothing in your activities

class MainActivity : BaseActivity<ActivityMainBinding>(ActivityMainBinding::inflate)
like image 58
Sinner of the System Avatar answered Sep 20 '22 12:09

Sinner of the System


It's cleaner to override binding object getter inside the child activity I think. So:

abstract class VBActivity<VB : ViewBinding> : AppCompatActivity() {
  protected abstract val binding: VB

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

And lets say MainActivity will be something like:

class MainActivity : VBActivity<ActivityMainBinding>() {

  override val binding get() = ActivityMainBinding.inflate(layoutInflater)

}
like image 44
Reza Avatar answered Sep 20 '22 12:09

Reza