<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<Button
android:id="@+id/button"
android:layout_width="150dp"
android:layout_height="150dp"
/>
<TextView
android:id="@+id/text_view"
android:layout_width="150dp"
android:layout_height="150dp"
/>
</LinearLayout>
View.OnTouchListener listener = new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
String view = "";
switch (v.getId()) {
case R.id.button:
view = "button";
break;
case R.id.text_view:
view = "text_view";
break;
}
Log.i(view, "event.getAction: " + event.getAction());
return false;
}
};
View btn = this.findViewById(R.id.button);
btn.setOnTouchListener(listener);
btn = this.findViewById(R.id.text_view);
btn.setOnTouchListener(listener);
输出:
button: event.getAction: 0
button: event.getAction: 1
button: event.getAction: 0
button: event.getAction: 2
button: event.getAction: 2
button: event.getAction: 2
button: event.getAction: 2
button: event.getAction: 2
button: event.getAction: 2
button: event.getAction: 2
button: event.getAction: 1
text_view: event.getAction: 0
text_view: event.getAction: 0
text_view: event.getAction: 0
text_view: event.getAction: 0
text_view: event.getAction: 0
问题:为什么要为Button发送ACTION_UP和ACTION_MOVE事件,而不是为TextView发送事件?
答案 0 :(得分:0)
如果触摸了按钮,则默认活动。 dispatchTouchEvent ()会为ACTION_DOWN返回 true ,如果触摸了TextView,则返回 false 。这种差异导致问题中提到的行为。