我创建自定义 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/