对 XML 中的一个或多个视图使用相同的单击事件
当我们在布局中创建任何 View 时,我们可以使用 android:onClick 属性来引用相关活动或片段中的方法来处理 click 事件。
XML 布局
<Button android:id="@+id/button"
...
// onClick should reference the method in your activity or fragment
android:onClick="doSomething" />
// Note that this works with any class which is a subclass of View, not just Button
<ImageView android:id="@+id/image"
...
android:onClick="doSomething" />
活动/片段代码
在你的代码中,创建你命名的方法,其中 v 将是被触摸的视图,并为调用此方法的每个视图执行某些操作。
public void doSomething(View v) {
switch(v.getId()) {
case R.id.button:
// Button was clicked, do something.
break;
case R.id.image:
// Image was clicked, do something else.
break;
}
}
如果需要,你还可以为每个 View 使用不同的方法(在这种情况下,你当然不必检查 ID)。