2

我知道关于这个话题有很多问题。我已经看过其中的大多数,但我仍然无法调试我的代码。它不检测滑动。我是 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;
        }
    
    }
    

    }

提前致谢。

4

1 回答 1

0

移动

LinearLayout swipe_layout= (LinearLayout)findViewById(R.id.linear); 

setContentView(R.layout.activity_main);Activity 之后,因为您试图在为当前 Activity 设置布局之前找到视图

并将onTouchListener布局设置为:

LinearLayout swipe_layout;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    swipe_layout= (LinearLayout)findViewById(R.id.linear);

    swipe_layout.setOnTouchListener(new OnTouchListener() {

     @Override
       public boolean onTouch(View v, MotionEvent event) {

         return true;
    }
  });
于 2013-01-06T08:48:10.810 回答