沒有直接的方法來使用Activity
而是作爲@ S.D調用的方法。指出的那樣,你可以使用ViewGroup
的onInterceptTouchEvent
做到這一點:
MyLinearLayout.java
public class MyLinearLayout extends LinearLayout {
public MyLinearLayout(Context context) {
super(context);
}
public MyLinearLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MyLinearLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@TargetApi(21)
public MyLinearLayout(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
@Override
public boolean onInterceptTouchEvent(final MotionEvent ev) {
Log.e("TOUCHES", "num: " + ev.getPointerCount());
return super.onInterceptTouchEvent(ev);
}
}
mylayout.xml
<mypackage.MyLinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/t1"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.5"
android:clickable="true"
android:gravity="center"
android:text="0"/>
<TextView
android:id="@+id/t2"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.5"
android:clickable="true"
android:gravity="center"
android:text="0"/>
</mypackage.MyLinearLayout>
MyActivity.java
public class MapsActivity extends FragmentActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mylayout);
final TextView t1 = (TextView) findViewById(R.id.t1);
final TextView t2 = (TextView) findViewById(R.id.t2);
t1.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(final View view, final MotionEvent motionEvent) {
t1.setText(""+motionEvent.getPointerCount());
return true;
}
});
t2.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(final View view, final MotionEvent motionEvent) {
t2.setText(""+motionEvent.getPointerCount());
return true;
}
});
}
}
這個例子將設置t1和t2 TextView
s的每個TextView
收到MotionEvent
的getPointerCount()
的文本,將記錄由MyLinearLayout
所有視圖都駐留在ViewGroup中作爲根視圖。 ViewGroup類有方法:['onInterceptTouch()'](https://developer.android.com/reference/android/view/ViewGroup.html#onInterceptTouchEvent(android.view.MotionEvent))。只要你從它返回false,事件就會通過它,然後傳遞給子視圖。因此,理論上,視圖的父ViewGroup可以監視所有的指針。你需要測試是確定的。 –