我看到了这个SO question ,并希望为自定义 View 实现可接受的答案。
因为在我的自定义 View 的 xml 中,它无法识别任何按钮的 android:onClick
方法!我想知道是否是因为自定义 View ,也许我应该只在 Activity 的 xml 中使用 onClick 方法。
是否可以在用户定义的自定义 View (扩展 LinearLayout)中为按钮 android:onClick
属性设置方法,如下所示:
这是我的自定义 View :
public class CustomEditText extends LinearLayout{
...
public void myMethod(View v) {
switch (v.getId()) {
case R.id.btn_down:
// do stuff;
break;
case R.id.btn_down_double:
// do stuff;
break;
}
}
}
这是我的 xml 文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:focusable="true"
android:focusableInTouchMode="true"
android:orientation="horizontal">
<LinearLayout
android:layout_height="wrap_content"
android:layout_weight="wrap_content"
android:background="@drawable/bg_ctrl"
android:orientation="vertical">
<android.support.v7.widget.AppCompatButton
android:id="@+id/btn_down"
style="@style/CustomButton"
android:onClick="myMethod"
android:theme="@style/CustomButton.RED" />
<android.support.v7.widget.AppCompatButton
android:id="@+id/btn_down_double"
style="@style/CustomButton"
android:onClick="myMethod"
android:theme="@style/CustomButton.RED2" />
</LinearLayout>
</LinearLayout>
错误是:
FATAL EXCEPTION: main
java.lang.IllegalStateException: Could not find method myMethod(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatButton with id 'btn_down'
更新:
此自定义 View 的父级是一个 fragment ,我将 myMethod()
移动到该 fragment ,但错误仍然存在:-|
最佳答案
这必须在您的 Activity 类代码中:
public void myMethod(View v) {
switch (v.getId()) {
case R.id.btn_down:
// do stuff;
break;
case R.id.btn_down_double:
// do stuff;
break;
}
}
关于android - 如何设置android :onClick in xml of a custom view?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35533020/