安卓判断滑动方向onTouchEvent

该博客详细介绍了如何在Android中通过onTouchEvent方法判断用户的滑动方向。通过记录ACTION_DOWN和ACTION_UP时的坐标,计算滑动的水平和垂直距离,根据距离大小判断是左右滑还是上下滑,并设置了相应的背景颜色提示。
public class MainActivity extends Activity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initview();
}


private void initview() {
textView = (TextView) findViewById(R.id.tv1);


}


float x_temp01 = 0.0f;
float y_temp01 = 0.0f;
float x_temp02 = 0.0f;
float y_temp02 = 0.0f;
private TextView textView;


@Override
public boolean onTouchEvent(MotionEvent event) {
// 获得当前坐标


switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
x_temp01 = event.getX();
y_temp01 = event.getY();


break;
case MotionEvent.ACTION_UP:
x_temp02 = event.getX();
y_temp02 = event.getY();
direction();


break;


}
return super.onTouchEvent(event);
}


private void direction() {
float h = x_temp02 - x_temp01;
float l = y_temp02 - y_temp01;


if (Math.abs(h) > Math.abs(l)) {
if (h > 0)// 向左
{
// 移动了x_temp01-x_temp02
textView.setText("向左滑动");
textView.setBackgroundColor(Color.BLUE);
} else {


// 移动了x_temp02-x_temp01
textView.setText("向右滑动");
textView.setBackgroundColor(Color.GREEN);
}


} else {
if (l > 0)// 向下
{


textView.setText("向下滑动");
textView.setBackgroundColor(Color.RED);
} else {


textView.setText("向上滑动");
textView.setBackgroundColor(Color.YELLOW);
}
}


// 比较x_temp01和x_temp02
// x_temp01>x_temp02 //向左
// x_temp01==x_temp02 //竖直方向或者没动
// x_temp01<x_temp02 //向右


}
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值