android supportV4包提供了一个强大的Layout——SlidingPaneLayout,这个布局可以实现侧滑菜单,关于怎么使用这里就不再介绍了,搜一下就会有很多使用的例子,这里只介绍使用SlidingPaneLayout实现滑动返回。
思路:
1.将SlidingPaneLayout左侧view背景设置为透明;
2.监听滑动事件,当左侧view完全展示时关闭当前Activity。
代码很简单
public class DragBackLayout extends SlidingPaneLayout implements SlidingPaneLayout.PanelSlideListener {
private Context context;
private Activity activity;
private boolean mFirstLayout = true;
public DragBackLayout(Context context, AttributeSet attrs) {
super(context, attrs);
this.context = context;
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
super.onLayout(changed, l, t, r, b);
initView();
}
private void initView(){
//如果已经添加过,则不再添加
if(!mFirstLayout){
return;
}
ViewGroup.LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
//透明布局
FrameLayout transparentLayout = new FrameLayout(context);
//设置透明背景
transparentLayout.setBackgroundColor(Color.TRANSPARENT);
addView(transparentLayout, 0, lp);
mFirstLayout = false;
}
/**
* 设置滑动返回
* @param activity
*/
public void setDragBack(Activity activity){
setPanelSlideListener(this);
this.activity = activity;
}
@Override
public void onPanelSlide(View panel, float slideOffset) {
}
@Override
public void onPanelOpened(View panel) {
if(this.activity != null){
activity.finish();
activity.overridePendingTransition(0, 0);
}
}
@Override
public void onPanelClosed(View panel) {
}
}
页面布局:
<?xml version="1.0" encoding="utf-8"?>
<com.lc.view.DragBackLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/activity_test"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#000000">
<android.support.v7.widget.RecyclerView
android:id="@+id/activity_test_rv"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
</com.lc.view.DragBackLayout>
Java代码
dbl = (DragBackLayout) findViewById(R.id.activity_test);
dbl.setDragBack(this);
效果