目的是什么?
在其他一些答案中,您可以看到使警告消失的方法,但重要的是要首先了解系统为什么要您覆盖 performClick()。
世界上有数以百万计的盲人。也许你通常不会想太多,但你应该。他们也使用安卓。 “如何?”你可能会问。一种重要的方式是通过TalkBack 应用程序。它是一个提供音频反馈的屏幕阅读器。您可以在手机中打开它,方法是转到设置 > 辅助功能 > TalkBack。通过那里的教程。这真的很有趣。现在尝试闭上眼睛使用您的应用程序。您可能会发现您的应用程序充其量是非常烦人的,最坏的情况是完全损坏。这对你来说是一个失败,任何有视力障碍的人都可以快速卸载。
观看 Google 制作的精彩视频,了解如何让您的应用易于访问。
如何覆盖performClick()
让我们看一个示例自定义视图,以了解覆盖 performClick() 的实际工作原理。我们将制作一个简单的导弹发射应用程序。自定义视图将是触发它的按钮。
启用 TalkBack 听起来会好很多,但动画 gif 不允许音频,因此您只能自己尝试。
代码
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<net.example.customviewaccessibility.CustomView
android:layout_width="200dp"
android:layout_height="200dp"
android:contentDescription="Activate missile launch"
android:layout_centerInParent="true"
/>
</RelativeLayout>
注意我设置了contentDescription。这样一来,TalkBack 就可以在用户感觉到自定义视图时读出自定义视图是什么。
CustomView.java
public class CustomView extends View {
private final static int NORMAL_COLOR = Color.BLUE;
private final static int PRESSED_COLOR = Color.RED;
public CustomView(Context context) {
super(context);
init();
}
public CustomView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init();
}
public CustomView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
setBackgroundColor(NORMAL_COLOR);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
super.onTouchEvent(event);
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
setBackgroundColor(PRESSED_COLOR);
return true;
case MotionEvent.ACTION_UP:
setBackgroundColor(NORMAL_COLOR);
// For this particular app we want the main work to happen
// on ACTION_UP rather than ACTION_DOWN. So this is where
// we will call performClick().
performClick();
return true;
}
return false;
}
// Because we call this from onTouchEvent, this code will be executed for both
// normal touch events and for when the system calls this using Accessibility
@Override
public boolean performClick() {
super.performClick();
launchMissile();
return true;
}
private void launchMissile() {
Toast.makeText(getContext(), "Missile launched", Toast.LENGTH_SHORT).show();
}
}
注意事项
进一步研究