I am trying to create a custom view which contains two buttons say OK and Cancel. I have two methods in my view model say fun onOkClicked(view View)
and fun onCancelClicked(view View)
. How can I pass these functions through XML layout file like android:onClick="methodName"
where we can pass a function from a context from activity or view model so the passed method get called when these buttons clicked. Is it possible to create custom attributes like onCreate
? I am aware of creating custom attributes but I am stuck in getting and invoking the functions that passed from the context.
Asked
Active
Viewed 339 times
0

Ruthwik Warrier
- 187
- 2
- 14
-
Did you try this way? https://stackoverflow.com/questions/44150912/android-viewmodel-livedata-update-view-on-button-click – Manikandan K Dec 13 '19 at 09:28
-
1You could have a look at how it's done in `View`: https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/view/View.java#6094. Basically, after you get the method name from the attributes, you instantiate a `DeclaredOnClickListener` with it, and set that as the `OnClickListener` on your inner `Button`. – Mike M. Dec 13 '19 at 09:38
1 Answers
0
As you using the viewmodel, so might aware about the databinding, it can help you to pass viewmodel into xml.
Little guidance of DataBinding just in case
Now you custom view xml should look like this from top
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto">
<data>
<variable
name="viewModel"
type="com.samples.LoginViewModel" />
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
android:padding="20dp">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
tools:fontPath=""
android:onClick="@{(v) -> viewModel.onOkClicked()}"
android:text="Ok" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:onClick="@{(v) -> viewModel.onCancelClicked()}"
android:text="Cancel" />
</LinearLayout>
</layout>
and in your data class, you can use it like below.
let say your xml name : custom_view.xml
So, in your Fragment/Activity/View
val binding: CustomViewBinding = CustomViewBinding.inflate(inflater, container, false)
binding.lifecycleOwner = viewLifecycleOwner
binding.viewModel = viewModel
binding.executePendingBindings()
Let me know if that helps.

Anil Prajapati
- 457
- 3
- 10