为什么 ACTION_UP 对 Button 和 TextView 的作用不同?
Why ACTION_UP works different for Button and TextView?
<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
问题:为什么 ACTION_UP 和 ACTION_MOVE 事件是为 Button 发送的,而不是为 TextView 发送的?
默认Activity.dispatchTouchEvent() returns true为ACTION_DOWN if触摸 Button 并且 returns false 如果触摸 TextView。这种差异会导致问题中提到的行为。
<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
问题:为什么 ACTION_UP 和 ACTION_MOVE 事件是为 Button 发送的,而不是为 TextView 发送的?
默认Activity.dispatchTouchEvent() returns true为ACTION_DOWN if触摸 Button 并且 returns false 如果触摸 TextView。这种差异会导致问题中提到的行为。