主要是有时候一些控件,你需要对控件的滑动情况做判断,恰好遇到这个,写个日志记录一下,你们看到的人,就直接用这个代码吧
1.运行效果:手机运行,滑动对照着日志测试了很多遍,发现很准确,没有出错的情况
04-18 18:03:42.631 31286-31286/com.example.longshine.zname E/TAG: wang向右
04-18 18:03:43.981 31286-31286/com.example.longshine.zname E/TAG: wang向左
04-18 18:03:44.559 31286-31286/com.example.longshine.zname E/TAG: wang向左
04-18 18:03:45.050 31286-31286/com.example.longshine.zname E/TAG: wang向左
04-18 18:03:45.692 31286-31286/com.example.longshine.zname E/TAG: wang向右
04-18 18:03:46.344 31286-31286/com.example.longshine.zname E/TAG: wang向右
2.因为东西过于简单,我就直接上代码吧
public class MainActivity extends AppCompatActivity {
private Button btn;
private ImageView coverImage;
private float mPosX, mPosY, mCurPosX, mCurPosY;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.button);
coverImage = (ImageView) findViewById(R.id.coverImage);
btn.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
mPosX = event.getX();
mPosY = event.getY();
break;
case MotionEvent.ACTION_MOVE:
mCurPosX = event.getX();
mCurPosY = event.getY();
break;
case MotionEvent.ACTION_UP:
if (mCurPosX - mPosX > 0
&& (Math.abs(mCurPosX - mPosX) > 25)) {
Log.e("TAG", "wang向右");
} else if (mCurPosX - mPosX < 0
&& (Math.abs(mCurPosX - mPosX) > 25)) {
Log.e("TAG", "wang向左");
}
break;
/* if (mCurPosY - mPosY > 0
&& (Math.abs(mCurPosY - mPosY) > 25)) {
Log.e("TAG", "wang向下");
} else if (mCurPosY - mPosY < 0
&& (Math.abs(mCurPosY - mPosY) > 25)) {
Log.e("TAG", "wang向上");
}
break;*/
}
return false;
}
});
}
}
上面存在一个参考网址,大家可以了解一下