![](/img/trans.png)
[英]Java redirect class method not found, needed for Android onClick from xml layout
[英]Android XML layout checkbox “onclick” method bind to a function not found in MainActivity
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?
像這樣的東西
//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
}
}
謝謝!
是的你可以。 我已經做了。 在你的布局文件中寫下這段代碼:
<CheckBox
android:layout_width="match_parent"
android:layout_height="match_parent"
android:onClick="click"/>
在您的活動中:
public void click(View view)
{
}
是的。 這是可能的。
要為復選框定義單擊事件處理程序,您應該將 android:onClick 屬性添加到 XML 布局中的元素。 此屬性的值必須是您要調用以響應單擊事件的方法的名稱。 托管布局的 Activity 必須實現相應的方法。
您在 android:onClick 屬性中聲明的方法必須具有完全如上所示的簽名。 具體來說,該方法必須: 1. 公開 2. 返回 void,以及 3. 將 View 定義為其唯一參數(這將是被點擊的 View)
下面是代碼示例: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>
活動方法應如下所示:
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
}
}
我希望你覺得這有幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.