【发布时间】:2013-01-06 08:34:10
【问题描述】:
我知道有很多关于这个话题的问题。我已经看过其中的大多数,但我仍然无法调试我的代码。它不检测滑动。我是 Android 编程和 Java 的初学者,所以请不要太挑剔。
- 我有一个简单的线性布局,带有一个填充整个布局的按钮。每次单击按钮时,其值都会增加 1。
- 我正在尝试实现向左向右滑动。我的基本疑问是我应该使用按钮还是线性布局来实现 setOnTouchListener?
-
我见过人们使用 OnGestureListener 和 OnTouchListener。哪一个更可取?
public class MainActivity extends Activity implements OnClickListener{ public Button increment; public int cnt= 0; private static final int SWIPE_MIN_DISTANCE = 80; private static final int SWIPE_THRESHOLD_VELOCITY = 40; GestureDetector gestureDetector; LinearLayout swipe_layout= (LinearLayout)findViewById(R.id.linear); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); increment= (Button)findViewById(R.id.numberkey); increment.setOnClickListener(this); setDisplay(0); gestureDetector= new GestureDetector(this, new Detector()); increment.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { gestureDetector.onTouchEvent(event); return true; } }); } @Override public void onClick(View v) { setDisplay(cnt++); } private void setDisplay(int i) { increment.setText(String.valueOf(i)); } class Detector extends SimpleOnGestureListener { @Override public boolean onDown(MotionEvent e) { return true; } @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { // right to left swipe if(e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) Toast.makeText(MainActivity.this, "Left Swipe", Toast.LENGTH_SHORT).show(); else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) { Toast.makeText(MainActivity.this, "Right Swipe", Toast.LENGTH_SHORT).show(); } return false; } }}
提前致谢。
【问题讨论】:
-
但是我应该用布局而不是按钮调用 onTouchListener 吗?按钮填充整个布局。
-
是的,你可以用 layout 来调用它
标签: android swipe touch-event uiswipegesturerecognizer swipe-gesture