Is it possible in Android to bind the "onclick" method from a checkbox to a function defined in a java class file directly in the XML file?
something like this
//XML layout File
....
<CheckBox
android:id="@+id/checkbox_1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/testString"
android:textColor="@color/testcolor"
android:onClick="onClickCheckbox_1_do"/>
...
public class TestClass{
...
public void onClickCheckbox_1_do(View view) {
//DoStuff
}
}
Thanks!
Yes, you can. I just did. Write this code in your layout file:
<CheckBox
android:layout_width="match_parent"
android:layout_height="match_parent"
android:onClick="click"/>
And in your activity:
public void click(View view)
{
}
Yes. it's possible.
To define the click event handler for a checkbox, you should add android:onClick attribute to the element in your XML layout. The value for this attribute must be the name of the method you want to call in response to a click event. The Activity hosting the layout must then implement the corresponding method.
The method you declare in the android:onClick attribute must have a signature exactly as shown above. Specifically, the method must: 1. Be public 2. Return void, and 3. Define a View as its only parameter (this will be the View that was clicked)
Below is the code examples: xml.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<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"/>
</LinearLayout>
The activity method should look as follows:
public void onCheckboxClicked(View view) {
// Is the view now checked?
boolean checked = ((CheckBox) view).isChecked();
// Check which checkbox was clicked
switch(view.getId()) {
case R.id.checkbox_meat:
if (checked)
// Put some meat on the sandwich
else
// Remove the meat
break;
case R.id.checkbox_cheese:
if (checked)
// Cheese me
else
// I'm lactose intolerant
break;
// TODO: Veggie sandwich
}
}
I hope you find this helpful.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.