android 右滑關閉activity
阿新 • • 發佈:2019-02-07
自定義實現了一個開發過程中遇到的一個需求。即右滑關閉當前acitvity,沒有像某個大神一樣考慮那麼多情況,只是滿足個人需要。
下面看實現
- 定義View
/**
* 用於右滑關閉activity
* @author Richard
*
*/
public class RightSlideFinishView extends FrameLayout {
private GestureDetector mGD;
private Activity mActivity;
public RightSlideFinishView(Context context) {
super (context);
mGD = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
int dx = (int) (e2.getX() - e1.getX()); // 計算滑動的距離
if (Math.abs(dx) > 100 && Math.abs(velocityX) > Math.abs(velocityY)) { // 降噪處理,必須有較大的動作才識別
if (velocityX > 0) {
//向右邊
mActivity.finish();
} else {
// 向左邊
Log.i("aaa","aaa");
}
return true;
} else {
return false; // 當然可以處理velocityY處理向上和向下的動作
}
}
});
}
// 接下來是重點,讓我們的View接受觸控
@Override
public boolean onTouchEvent(MotionEvent event) {
mGD.onTouchEvent(event);
return true;
}
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
return mGD.onTouchEvent(event);
}
public void attachToActivity(Activity activity) {
mActivity = activity;
TypedArray a = activity.getTheme().obtainStyledAttributes(
new int[] { android.R.attr.windowBackground });
int background = a.getResourceId(0, 0);
a.recycle();
ViewGroup decor = (ViewGroup) activity.getWindow().getDecorView();
ViewGroup decorChild = (ViewGroup) decor.getChildAt(0);
decorChild.setBackgroundResource(background);
decor.removeView(decorChild);
addView(decorChild);
decor.addView(this);
}
2 . 使用
BaseActivity中新增如下程式碼,其他作為其他activity的父類
protected RightSlideFinishView layout;
layout=new RightSlideFinishView(this);
layout.attachToActivity(this);
Over~