我在网上看了很多例子,他们都有这样实现的gesturelistener。我不能让android拿起手势事件,myText的值不会改变,我在logcat中没有得到任何输出。我做错了什么?
public class MainActivity extends Activity {
private GestureDetector gDetector;
private TextView myText;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gDetector = new GestureDetector(this, new MyOnGestureListener());
myText = (TextView) findViewById(R.id.mytext);
myText.setText("Test");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
class MyOnGestureListener extends SimpleOnGestureListener implements
OnGestureListener {
@Override
public boolean onDown(MotionEvent e) {
Log.d("Main", "did");
myText.setText("hi");
// TODO Auto-generated method stub
return true;
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
myText.setText("hi");
Log.d("Main", "did");
// TODO Auto-generated method stub
return true;
}
@Override
public void onLongPress(MotionEvent e) {
Log.d("Main", "did");
myText.setText("hi");
// TODO Auto-generated method stub
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2,
float distanceX, float distanceY) {
Log.d("Main", "did");
myText.setText("hi");
// TODO Auto-generated method stub
return true;
}
@Override
public void onShowPress(MotionEvent e) {
Log.d("Main", "did");
myText.setText("hi");
// TODO Auto-generated method stub
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
Log.d("Main", "did");
myText.setText("hi");
// TODO Auto-generated method stub
return true;
}
}
}
答案 0 :(得分:7)
缺少的部分是您没有将GestureListener链接到触摸事件。
所以你可以像这样覆盖OnTouchListener:
@Override
public boolean onTouchEvent(MotionEvent me) {
return gDetector.onTouchEvent(me);
}
或者如果您想在特定视图上启用GestureDetector:
view.setOnTouchListener(new OnTouchListener{
@Override
public boolean onTouchEvent(MotionEvent me) {
return gDetector.onTouchEvent(me);
}
})
答案 1 :(得分:4)
您需要使用字段gDetector。到目前为止,您只创建了一个实例,但现在您必须使用它来获取结果。
例如:
this.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(final View view, final MotionEvent event) {
return gDetector.onTouchEvent(event);
}
});
答案 2 :(得分:0)
试试此代码here
这应该有用。
也改变了行
gestureScanner = new GestureDetector(this);
到
gestureScanner = new GestureDetector(ScrollTest.this, this);