您的位置:首页 > 移动开发 > Android开发

Android滑动返回上一级界面

2016-12-01 00:00 381 查看
自定义Activity布局的root控件,拦截触摸事件并拦截

拦截触摸事件函数onInterceptTouchEvent

event.getAction() == MotionEvent.ACTION_DOWN return true;Move Up 事件不再传递

父控件的onTouchEvent函数处理所有的滑动事件

注意一点onTouchEvent函数中event.getAction() == MotionEvent.ACTION_DOWN return true;这里如果返回false的,事件直接结束,Move Up事件不再传递。

public class SwipeBackFrameLayout extends FrameLayout {
float eventX;
private String TAG = SwipeBackFrameLayout.class.getName();

public SwipeBackFrameLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}

@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: {
Log.d(TAG, "MotionEvent.ACTION_DOWN");
float eventX = event.getX();
if (eventX < 55) {
return true;
}
break;
}
}
return super.onInterceptTouchEvent(event);
}

@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: {
Log.d(TAG, "MotionEvent.ACTION_DOWN");
eventX = event.getX();
return true;
}
case MotionEvent.ACTION_MOVE: {
Log.d(TAG, "MotionEvent.ACTION_MOVE");
float eventXM = event.getX();
float differenceXM = eventXM - eventX;
if (differenceXM > 30) {
((Activity) getContext()).finish();
}
return true;
}
case MotionEvent.ACTION_UP: {
Log.d(TAG, "MotionEvent.ACTION_UP");
return true;
}

}
return super.onTouchEvent(event);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  滑动返回