1、在styles文件中,给主题添加<item name="android:windowIsTranslucent">true</item>
2、项目中添加 SwipeBackLayout.java 和 SwipeBackActivity.java 文件(文件如下),并使Activity继承SwipeBackActivity即可实现简单的右滑删除效果
SwipeBackLayout.java文件SwipeBackActivity.java文件public class SwipeBackActivity extends AppCompatActivity { private SwipeBackLayout mSwipeBackLayout; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); getWindow().getDecorView().setBackgroundDrawable(null); } @Override public void setContentView(@LayoutRes int layoutResID) { mSwipeBackLayout = new SwipeBackLayout(this); View childView = View.inflate(this, layoutResID, null); mSwipeBackLayout.addView(childView); super.setContentView(mSwipeBackLayout); } @Override public void setContentView(View view) { mSwipeBackLayout = new SwipeBackLayout(this); mSwipeBackLayout.addView(view); super.setContentView(mSwipeBackLayout); } }
public class SwipeBackLayout extends RelativeLayout { private ViewDragHelper helper; private float mScrollPercent; private float mScrollThreshold = 0.5f; private static final int OVER_SCROLL_DISTANCE = 10; public SwipeBackLayout(Context context) { super(context); init(); } public SwipeBackLayout(Context context, AttributeSet attrs) { super(context, attrs); init(); } public SwipeBackLayout(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } private void init() { helper = ViewDragHelper.create(this, 1.0f, new ViewDragHelper.Callback() { @Override public boolean tryCaptureView(View child, int pointerId) { boolean ret = helper.isEdgeTouched(ViewDragHelper.EDGE_LEFT, pointerId); return ret; } @Override public void onViewPositionChanged(View changedView, int left, int top, int dx, int dy) { super.onViewPositionChanged(changedView, left, top, dx, dy); mScrollPercent = Math.abs((float) left / getWidth()); invalidate(); if (mScrollPercent >= 1) { Activity act = (Activity) getContext(); if (!act.isFinishing()) { act.finish(); act.overridePendingTransition(0, 0); } } } @Override public void onViewReleased(View releasedChild, float xvel, float yvel) { int left = xvel > 0 || xvel == 0 && mScrollPercent > mScrollThreshold ? getWidth() + OVER_SCROLL_DISTANCE : 0; helper.settleCapturedViewAt(left, 0); invalidate(); } @Override public int getViewHorizontalDragRange(View child) { return 1; } @Override public int clampViewPositionHorizontal(View child, int left, int dx) { return Math.max(0, left); } }); helper.setEdgeTrackingEnabled(ViewDragHelper.EDGE_LEFT); } @Override public void computeScroll() { if (helper.continueSettling(true)) { ViewCompat.postInvalidateOnAnimation(this); } } @Override public boolean onInterceptTouchEvent(MotionEvent ev) { boolean ret = helper.shouldInterceptTouchEvent(ev); return ret; } @Override public boolean onTouchEvent(MotionEvent event) { helper.processTouchEvent(event); return true; } }