Skip to content

Instantly share code, notes, and snippets.

@n8ebel
Last active February 27, 2023 22:31
Show Gist options
  • Save n8ebel/c2fe662418863f30c409e93eb2cef42c to your computer and use it in GitHub Desktop.
Save n8ebel/c2fe662418863f30c409e93eb2cef42c to your computer and use it in GitHub Desktop.
Basic example of using databinding to handle button clicks
  • Use a viewmodel to bind the data
  • Bind the Button's onClick method to MainViewModel.handleClick()
  • Use a custom @BoundFunction annotation to make the viewmodel code more self-documenting

Code

<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<data>
<variable
name="viewModel"
type="com.n8ebel.databindingsandbox.MainViewModel" />
</data>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="@{viewModel.message}"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text='@{"And here we are binding a simple value like the number " + viewModel.number}'
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click Me"
android:onClick="@{() -> viewModel.handleClick()}"
/>
</LinearLayout>
</layout>
class MainActivity : AppCompatActivity(), ViewModelListener {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding = DataBindingUtil.setContentView<ActivityMainBinding>(this, R.layout.activity_main).bindData {
viewModel = MainViewModel("hello", 5, this@MainActivity)
}
}
// region implements ViewModelListener
override fun showMessage(message: String) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
}
// endregion implements ViewModelListener
}
class MainViewModel(msg:String, num:Int, val listener:ViewModelListener) {
val message = ObservableField<String>(msg)
val number = ObservableInt(num)
@BoundFunction
fun handleClick() {
listener.showMessage("You Clicked It!!")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment