Android 固定式底部上滑抽屉view

1、自定义view  BottomDrawerLayout

/**
 * 作者:created by meixi
 * 邮箱:15913707499@163.com
 * 日期:2018/12/10 11
 */

public class BottomDrawerLayout extends ViewGroup {

    private static final String TAG = "BottomDrawerLayout";

    private View mDrawerView;
    private View mBottomView;

    private View mRotateView;

    private ViewDragHelper mDragHelper;
    private float mInitialX;
    private float mInitialY;
    private int mTouchSlop;
    private int mCurTop=-1;
    private int mBottomHeight;
    private int mDrawerHeight;
    private int mParentHeight;
    private float mDragOffset = 1;
    private boolean isUnderBottomView = false;
    private boolean isUnderDrawerView = false;
    private OnDrawerStatusChanged onDrawerStatusChanged;


    public BottomDrawerLayout(Context context) {
        super(context);
        init(context);
    }

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

    public BottomDrawerLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    private void init(Context context) {
        mDragHelper = ViewDragHelper.create(this, 1.0f,new DragerCallBack());
        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
    }



    public void setOnDrawerStatusChanged(OnDrawerStatusChanged onDrawerStatusChanged) {
        this.onDrawerStatusChanged = onDrawerStatusChanged;
    }

    public void switchDrawer() {
        if(mDragOffset<1){
            minimize();
        }else{
            maximize();
        }
    }

    private class DragerCallBack extends  ViewDragHelper.Callback{

        //从底部到顶部的顺序遍历子view
        @Override
        public int getOrderedChildIndex(int index) {
            int childCount = BottomDrawerLayout.this.getChildCount();
            int newIndex = childCount - index -1;

            return  newIndex;
        }

        @Override
        public boolean tryCaptureView(View child, int pointerId) {

            return child == mDrawerView;
        }

        @Override
        public int clampViewPositionHorizontal(View child, int left, int dx) {
//            Log.d(TAG, "clampViewPositionHorizontal " + left + "," + dx);
//            final int leftBound  = getPaddingLeft();
//            final int rightBound = getWidth() - mBottomView.getWidth() - leftBound;
//            //坐标系三种情况
//            final int newLeft = Math.min(Math.max(left, leftBound), rightBound);
//
//            return newLeft;

            return super.clampViewPositionHorizontal(child, left, dx);
        }

        //要想上下拖动必须重写此方法
        @Override
        public int clampViewPositionVertical(View child, int top, int dy) {
//            Log.d(TAG, "clampViewPositionVertical " + top + "," + dy);

            final int topBound = getHeight() - mDrawerView.getMeasuredHeight() - mBottomView.getHeight();
            final int bottomBound = getHeight()  - mBottomView.getHeight();
            final int newTop = Math.min(Math.max(top, topBound), bottomBound);

            return newTop;
        }

        @Override
        public void onViewCaptured(View capturedChild, int activePointerId) {
            super.onViewCaptured(capturedChild, activePointerId);
        }


        @Override
        public void onViewReleased(View releasedChild, float xvel, float yvel) {

//            Log.i(TAG, "onViewReleased:" + "xvel:" + xvel + ",yvel:" + yvel);
            //yvel Fling产生的值,yvel > 0 则是快速往下Fling || yvel < 0 则是快速往上Fling

            int top = mParentHeight - mDrawerHeight - mBottomHeight;
            if (yvel > 0 || (yvel == 0 && mDragOffset > 0.5f)/* 后面这个小括号里判断处理拖动之后停下来但是未松手的情况 */) {
                top += mDrawerHeight;
            }
            mDragHelper.settleCapturedViewAt(releasedChild.getLeft(), top);
            invalidate();//important 不加,就不会刷新View的位置
        }

        @Override
        public void onViewDragStateChanged(int state) {
            super.onViewDragStateChanged(state);
        }

        @Override
        public void onViewPositionChanged(View changedView, int left, int top, int dx, int dy) {
            mCurTop = top;
            mDragOffset = ((float) top -(mParentHeight - mDrawerHeight - mBottomHeight))/ mDrawerHeight;
//            Log.d(TAG, "onViewPositionChanged: mDragOffset:" + mDragOffset);

            //旋转与透明跟随效果
            mDrawerView.setAlpha(1-mDragOffset);
//            mRotateView.setRotation((1-mDragOffset)*180);
            requestLayout();

            if (onDrawerStatusChanged != null) {
                onDrawerStatusChanged.onChanged(mParentHeight,top);
            }


//            if(onDrawerStatusChanged !=null){
//                if(mDragOffset == 0 || mDragOffset == 1){
//                    onDrawerStatusChanged.onChanged(mParentHeight,top);
//                }
//            }
        }
    }

    public interface OnDrawerStatusChanged{
        void onChanged(int parentHeight, int drawerTop);
    }

    public void maximize()
    {
        smoothSlideTo(0.0f);
    }

    public void minimize()
    {
        smoothSlideTo(1.0f);
    }

    private boolean smoothSlideTo(float slideOffset) {
        final int topBound = mParentHeight - mDrawerHeight - mBottomHeight;
        int y = (int) (topBound + slideOffset * mDrawerHeight);

        if(mDragHelper.smoothSlideViewTo(mDrawerView, mDrawerView.getLeft(), y))
        {
            ViewCompat.postInvalidateOnAnimation(this);
            return true;
        }
        return false;
    }
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        return super.dispatchTouchEvent(ev);

    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent event) {

        int act = MotionEventCompat.getActionMasked(event);
//        final int action = event.getAction();

        switch (act) {
            //由于很多情况不能拦截事件,这种时候系统不会调用onTouchEvent()
            // 手动把事件传递给mDragHelper.processTouchEvent
            case MotionEvent.ACTION_DOWN:

                mInitialX = event.getX();
                mInitialY = event.getY();
                //Feed the down event to the detector so it has
                // context when/if dragging begins
//                mDetector.onTouchEvent(event);
                mDragHelper.processTouchEvent(event);
                isUnderBottomView = mDragHelper.isViewUnder(mBottomView, (int)mInitialX, (int)mInitialY);
                isUnderDrawerView = mDragHelper.isViewUnder(mDrawerView, (int)mInitialX, (int)mInitialY);
                break;
            case MotionEvent.ACTION_POINTER_DOWN:
                mDragHelper.processTouchEvent(event) ;
                break;
            case MotionEvent.ACTION_POINTER_UP:
                mDragHelper.processTouchEvent(event) ;
                break;
            case MotionEvent.ACTION_MOVE:

                final float x = event.getX();
                final float y = event.getY();
                final int yDiff = (int) Math.abs(y - mInitialY);
                final int xDiff = (int) Math.abs(x - mInitialX);
                //Verify that either difference is enough to be a drag
                if ((yDiff > mTouchSlop || xDiff > mTouchSlop) && (isUnderBottomView || isUnderDrawerView) ){
                    //Start capturing events
                    return true;
                }
                break;
        }

        //父类是viewgroup,返回的false
        return super.onInterceptTouchEvent(event);

    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {

        mDragHelper.processTouchEvent(event);
        //down事件返回false,让其底部的平行层级的view能够接收到点击事件
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                return false;
            case MotionEvent.ACTION_UP:
                return false;
            //只有当手指达到拖动阈值时this才确定消耗此系列事件
            //若未达到阈值也返回true,则与其平行的view不会收到click事件
            case MotionEvent.ACTION_MOVE:
                final float x = event.getX();
                final float y = event.getY();
                final int yDiff = (int) Math.abs(y - mInitialY);
                final int xDiff = (int) Math.abs(x - mInitialX);
                //Verify that either difference is enough to be a drag
                if ((yDiff > mTouchSlop || xDiff > mTouchSlop) && (isUnderBottomView || isUnderDrawerView) ){
                    //Start capturing events
                    return true;
                }

                break;
        }
        return false;
    }



    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();

        mBottomView = findViewById(R.id.layout_bottom_bar);
        mDrawerView = findViewById(R.id.layout_price_detail);

//        mRotateView = findViewById(R.id.img_spread_out);

        mBottomView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                maximize();
            }
        });

        mDrawerView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                minimize();
            }
        });
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        measureChildren(widthMeasureSpec,heightMeasureSpec);
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        mParentHeight = this.getHeight();
        mBottomHeight = mBottomView.getMeasuredHeight();

        mDrawerHeight = mDrawerView.getMeasuredHeight();
//        Log.d(TAG, "onLayout: drawHeight:"+drawHeight);


        mBottomView.layout(l,mParentHeight - mBottomHeight,r,b);
        if(mCurTop == -1){
            mCurTop = mParentHeight - mBottomHeight;
        }

        mDrawerView.layout(l,mCurTop,r,mCurTop + mDrawerHeight);

    }



    @Override
    public void computeScroll() {
        if(mDragHelper.continueSettling(true))
        {
            ViewCompat.postInvalidateOnAnimation(this);
        }
    }
}

layout布局中使用这个自定义抽屉view即可,第一个LinearLayout是抽屉内容,第二个LinearLayout是固定底部把手

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent">


    <com.tianxin.shanghuact.BottomDrawerLayout
        android:id="@+id/bottom_drawer_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout
            android:id="@+id/layout_price_detail"
            android:layout_width="match_parent"
            android:background="@color/colorPrimary"
            android:orientation="horizontal"
            android:layout_height="180dp">

        </LinearLayout>

        <LinearLayout
            android:id="@+id/layout_bottom_bar"
            android:layout_width="match_parent"
            android:background="@color/transparent"
            android:orientation="horizontal"
            android:layout_height="40dp">

        </LinearLayout>

    </com.tianxin.shanghuact.BottomDrawerLayout>

</RelativeLayout>

 抽屉demo连接:Android开发,抽屉viewdemo-Android文档类资源-CSDN下载

 

  • 3
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
Android 中,可以使用 NavigationDrawer 实现上下动的抽屉效果。以下是一些步骤: 1. 在布局文件中添加 DrawerLayout 和 NavigationView。 ```xml <androidx.drawerlayout.widget.DrawerLayout android:id="@+id/drawer_layout" android:layout_width="match_parent" android:layout_height="match_parent"> <!-- 主要内容 --> <FrameLayout android:id="@+id/content_frame" android:layout_width="match_parent" android:layout_height="match_parent" /> <!-- 抽屉 --> <com.google.android.material.navigation.NavigationView android:id="@+id/nav_view" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_gravity="start" app:menu="@menu/menu_drawer" /> </androidx.drawerlayout.widget.DrawerLayout> ``` 2. 在 Activity 中设置 DrawerLayout,并设置 ActionBar。 ```java private ActionBarDrawerToggle toggle; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // 设置 ActionBar setSupportActionBar(findViewById(R.id.toolbar)); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setHomeButtonEnabled(true); DrawerLayout drawer = findViewById(R.id.drawer_layout); // 设置抽屉的开关 toggle = new ActionBarDrawerToggle( this, drawer, R.string.navigation_drawer_open, R.string.navigation_drawer_close); drawer.addDrawerListener(toggle); toggle.syncState(); // 设置 NavigationView 的点击事件 NavigationView navigationView = findViewById(R.id.nav_view); navigationView.setNavigationItemSelectedListener(this); } // 处理 ActionBar 的点击事件 @Override public boolean onOptionsItemSelected(MenuItem item) { if (toggle.onOptionsItemSelected(item)) { return true; } return super.onOptionsItemSelected(item); } ``` 3. 在 res/menu 文件夹下创建 menu_drawer.xml 文件用于设置 NavigationView 的菜单项。 ```xml <menu xmlns:android="http://schemas.android.com/apk/res/android"> <group android:checkableBehavior="single"> <item android:id="@+id/nav_home" android:icon="@drawable/ic_home" android:title="Home" /> <item android:id="@+id/nav_gallery" android:icon="@drawable/ic_gallery" android:title="Gallery" /> <item android:id="@+id/nav_slideshow" android:icon="@drawable/ic_slideshow" android:title="Slideshow" /> </group> </menu> ``` 4. 处理 NavigationView 的点击事件。 ```java @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { int id = item.getItemId(); if (id == R.id.nav_home) { // 处理菜单项的点击事件 } else if (id == R.id.nav_gallery) { // 处理菜单项的点击事件 } else if (id == R.id.nav_slideshow) { // 处理菜单项的点击事件 } DrawerLayout drawer = findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); return true; } ``` 以上就是实现 Android 上下抽屉的基本步骤。
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值