[Android] DataBinding-ktx 2.2.0 Released

Takumi WADA
DataBinding-ktx
Published in
2 min readOct 2, 2019

DataBinding-ktx 3.0.1 has been released.

Original article is below.

What is DataBinding-ktx

A library for solving problems related to DataBinding and using it safely and easily.

About DataBinding-ktx

Please refer to the following for the problem that DataBinding-ktx solves.

About DataBinding-ktx 2.2.0

Supports variable declaration with top-level function

Converting existing code to Delegated Property is cumbersome, so we have prepared a top-level function that has fewer differences and is easy to handle with batch replacement.

 class DataBindingActivity : FragmentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
- val binding = DataBindingUtil.setContentView<DataBindingActivityBinding>(this, R.layout.data_binding_activity)
- binding.lifecycleOwner = this
+ val binding = setContentView<DataBindingActivityBinding>(this, R.layout.data_binding_activity)
}
}

In addition, Delegated Property can only be used from Kotlin, but by using Top-level function, it can be used in Java as follows.

public class DataBindingActivity extends FragmentActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
DataBindingActivityBinding binding = ActivityDataBinding.setContentView(this, R.layout.data_binding_activity);
}
}

Supports ViewBinding variable declaration

ViewBinding is a function that removes the binding function of DataBinding and only provides the function to access View by id.

ViewBinding can be used as follows.

class ViewBindingActivity : FragmentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding = ViewBindingActivityBinding.inflate(layoutInflater)
setContentView(binding.root)
}
}

Since the generated Binding class does not have a setContentView method, it must be set separately. Therefore, I made it possible to write as follows.

class ViewBindingActivity : FragmentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding = setContentView { ViewBindingActivityBinding.inflate(it) }
}
}

Also, like DataBinding, it can be declared with Delegated Property.

class ViewBindingActivity : FragmentActivity() {
private val binding: ViewBindingActivityBinding by viewBinding()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// use binding
}
}

However, unlike DataBinding, ViewBinding has no problem with the standard way of writing, so you don’t need to use it unless you want to use the Delegated Property method to unify the way of writing.
* Since ViewBinding does not have a class equivalent to DataBindingUtil, it is necessary to call the static method of the generated Binding class and uses reflection internally.

Click here for DataBinding-ktx 2.2.0

--

--