Data Binding
For Data Binding there's an extension function eliminating some boilerplate code:
class CalculatorActivity : AppCompatActivity()
private val viewModel: CalculatorViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
// extension function to eliminate boilerplate code
bind<ActivityCalculatorBinding>(R.layout.activity_calculator) { it.viewmodel = viewModel }
without a ViewModel:
class CalculatorActivity : AppCompatActivity()
val bloc by getOrCreate { calculatorBloc(it) }
override fun onCreate(savedInstanceState: Bundle?) {
// extension function to eliminate boilerplate code
bind<ActivityCalculatorBinding>(R.layout.activity_calculator) { it.activity = this }
The bind
function:
- sets the Activity's content view to the given layout
- binds the layout with a component (ViewModel or Activity in above examples)
- sets the LifecycleOwner that should be used for observing changes of LiveData in the binding
Sending ui events to the bloc happens in the standard data binding way, e.g. in combination with a ViewModel:
<data>
<variable
name="viewmodel"
type="com.onegravity.bloc.calculator.CalculatorViewModel" />
</data>
<Button
android:id="@+id/button_clear"
android:onClick="@{(view) -> viewmodel.onClick(view.id)}"/>
If no ViewModel is used (see getOrCreate()):
<data>
<variable
name="activity"
type="com.onegravity.bloc.calculator.CalculatorActivity" />
</data>
<Button
android:id="@+id/button_clear"
android:onClick="@{() -> activity.button(ActionEnum.Clear)}"/>