android - 如何设置android :onClick in xml of a custom view?

标签 android onclick onclicklistener android-custom-view buttonclick

我看到了这个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/

相关文章:

c# - Xamarin Forms ListView 程序刷新在页面加载时不会在 Android 上停止

android - OnSharedPreferenceChangeListener 和 editor.clear()

java - 为Android应用程序设置声音

javascript - 如何让js函数 "onClick"只在容器div上工作?

android - 动态表格布局上的 OnClickListener

android - 在 RecyclerView 中更改 ImageView 中的图像

android - FloatingActionButton 没有改变颜色

javascript - 每次点击时调用函数(HTML 包括框架)

android - 从 Android SQLite 数据库中删除

java - Android 致命异常空指针