Android 使用SlidingPaneLayout實現仿IOS滑動返回

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) {
    }

}

 

 

使用:

佈局文件

 

<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);

 

 


 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章