我有两个TextView
,我想仅为setOnTouchListener
设置TextView
。
我找到了this SO answer并按照这个答案的说明做了那个,但我无法解决问题。我正在使用GestureDetectorCompat
。我尝试了很多解决方案,但问题仍然存在。
当我触摸textview1
时,onFling
方法会从注册onTouch
侦听器调用,但当我触摸textview2
时,onFling
方法仍然是从life cycle method
开始调用。我没有理解为什么它在未注册的textview上调用onFling
。
请帮帮我。
acticity_main.xml
<TextView
android:layout_width="match_parent"
android:layout_height="100dp"
android:background="#ffcc99"
android:id="@+id/textview1"
android:layout_margin="20dp"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_gravity="bottom"
android:background="#ffcc88"
android:id="@+id/textview2"
android:text="Hello World!" />
MainActivity.java
import android.graphics.Path;
import android.os.Bundle;
import android.support.v4.view.GestureDetectorCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private static String DEBUG_TAG = "debug";
private TextView mTextView;
private GestureDetectorCompat mGestureDetector;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mGestureDetector = new GestureDetectorCompat(this,this);
findViewById(R.id.textview1).setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, final MotionEvent event) {
Log.e(DEBUG_TAG, "setOnTouchListener");
mGestureDetector.onTouchEvent(event);
return true;
}
});
}
@Override
public boolean onTouchEvent(MotionEvent event) {
Log.e(DEBUG_TAG, "onTouchEvent");
mGestureDetector.onTouchEvent(event);
return super.onTouchEvent(event);
}
@Override
public boolean onDown(MotionEvent e) {
Log.e(DEBUG_TAG, "onDown");
return false;
}
@Override
public void onShowPress(MotionEvent e) {
Log.e(DEBUG_TAG, "onShowPress");
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
Log.e(DEBUG_TAG, "onSingleTapUp");
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
Log.e(DEBUG_TAG, "onScroll");
return false;
}
@Override
public void onLongPress(MotionEvent e) {
Log.e(DEBUG_TAG, "onLongPress");
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
Log.e(DEBUG_TAG, "onFling " + e1.getX() + " - " + e2.getX());
}
}
答案 0 :(得分:1)
请移除onTouchEvent
之外的onCreate
方法,然后该方法仅适用于textview1
。由于您已在onTouchEvent
之外应用了onCreate
,因此只要整个MainActivity
出现手势事件,就会调用onTouchEvent
,因为onCreate
外的mGestureDetector.onTouchEvent(event)
也在调用 mGestureDetector.onTouchEvent(event);
声明
GestureDetectorCompact
自动调用OnGestureListener
来电的onTouchEvent,它确实会根据动作事件进行{{1}}提供的相应回调。