在android开发中,我们经常会用到一种非常方便的效果,就是左右或上下滑动进行切换内容或控件,比如要删除一条信息,向左滑动会出现一个删除功能键进行删除。
要实现这个功能我们就可以使用onTouch事件来处理,具体代码如下:
package com.example.text; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; import android.widget.TextView; public class MainActivity extends Activity { private TextView txtTest; private float moveX; private float moveY; private float pressX; private float pressY; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); txtTest = (TextView)findViewById(R.id.txtTest); txtTest.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()) { //按下 case MotionEvent.ACTION_DOWN: pressX = event.getX(); pressY = event.getY(); break; //移动 case MotionEvent.ACTION_MOVE: moveX = event.getX(); moveY = event.getY(); break; //松开 case MotionEvent.ACTION_UP: if (moveX-pressX > 0 && Math.abs(moveY - pressY) < 50) { Log.i("message", "向右"); } else if (moveX - pressX < 0 && Math.abs(moveY - pressY) < 50) { Log.i("message", "向左"); } break; default: break; } return true; } }); } }