安卓判断滑动方向onTouchEvent

来源:互联网 发布:淘宝小蜜是干嘛的 编辑:程序博客网 时间:2024/05/30 22:49
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 0
原创粉丝点击