Android, Checkbox listener in XML?
Official documentation: https://developer.android.com/guide/topics/ui/controls/checkbox.html
<CheckBox android:id="@+id/checkbox_meat" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/meat" android:onClick="onCheckboxClicked"/><CheckBox android:id="@+id/checkbox_cheese" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/cheese" android:onClick="onCheckboxClicked"/>
It is now possible to do this with the use of data binding library.First you need to create a handler class (in this example, I call it MainActivityHandlers). Inside this handler class, define a method (for example the name is method1) with the corresponding implementation Then in your layout file, you just need to implement :
... <data> <variable name="handler" type="com.test.android.testapp.MainActivityHandlers" /></data>... <RadioGroup ... android:onCheckedChanged="@{handler.method1}" ... >
and you're good to go.More info : https://developer.android.com/topic/libraries/data-binding/index.html
I believe using a lambda is more convenient:
<EditText android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/firstName" android:text="@={user.firstName}" /><CheckBox android:layout_width="wrap_content" android:layout_height="wrap_content" android:onCheckedChanged="@{()->handler.checked(firstName)}" />
For more details see this.
Also, I find the use of two way binding very useful for checkboxes:
<CheckBox android:layout_width="wrap_content" android:layout_height="wrap_content" android:checked='@={user.isChecked}'/>
Note that onCheckedChanged
is called before the two way binding sets the value.