java - 在 xml 中为 Android 中的自定义 View 设置 onClick 在某些版本上不起作用

标签 java android android-layout android-view android-custom-view

我创建自定义 View 并在某些 xml Activity 中使用它,然后设置 android:onClick="buttonOnClick"。我将 buttonOnClick 定义为 public 并将其写入其 Activity 并设置 tools:context
Activity.java

 public void buttonOnClick(View view) {
        validate(view);
    }

布局.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    ...
    tools:context="com.test.myapp.Activity">

   <com.test.myapp.GifImageViewComp
      ....
    android:onClick="buttonOnClick"  />

它正在 Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP 上运行,但在其他操作系统版本中,自定义 View xml onclick 属性尝试从 View 类而不是 Activity 中查找处理程序。

我不想在每个 View 上使用 onClick 或 setOnClickListener 的实现,我想在 Activity 布局中使用 onClick

最佳答案

It's just not clear the relationship between a button in your xml and a method in your activity that reacts to the click events unless you explicitly see it defined in your Java file. With the android:onClick approach you can even forget that you have a button in your layout or which is the method that is handling its onClick event.

<强> Source

您应该使用 OnClickListener 而不是 android:onClick

Interface definition for a callback to be invoked when a view is clicked.

此方法获取对监听器的引用,并注册单击 View 时要调用的回调。

仅供引用

确保在 XML 中设置 android:clickable="true" 。您应该指定此属性

<com.test.myapp.GifImageViewComp
    android:clickable="true"
    android:onClick="buttonOnClick"  />

关于java - 在 xml 中为 Android 中的自定义 View 设置 onClick 在某些版本上不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44715245/

相关文章:

java - 在 Arraylist 中搜索名称,如果没有找到返回重试

android - IAB 助手未设置。无法执行操作(Android 2.3.3)

php - 使用 where 子句检索 MySQL 数据

java - 如何获取设备原始宽度和高度或实际屏幕宽度和高度?

java - android.view.InflateException : Binary XML file line #2: Error inflating class <unknown>?

java.lang.ClassNotFoundException : javax. 持久性.NamedStoredProcedureQuery

java - 基元数组列表的 Mockito 匹配器

android - 在 android 中杀死我的应用程序后,Job Scheduler 不工作?

android - 布局更改不使用 animateLayoutChanges=true 设置动画?

java - 在字符串数组中查找大写字母并将其提取出来