自定义布局实现侧滑菜单2

来源:互联网 发布:时间校正软件 编辑:程序博客网 时间:2024/06/04 19:52
我们在上一节已经说了侧滑菜单的实现原理,并且实现了单侧菜单,这一节我们就完善项目,实现双向侧滑菜单。原理我们都说了,不明白的看上节,好了,直接上代码
/** * 这个类和SlidingLayout作用一样,只是没有实现触摸监听事件,直接在121行设置实现了 */public class SlidingLayout1 extends LinearLayout {    /**     * 滚动显示和隐藏左侧布局时,手指滑动需要达到的速度。     */    public static final int SNAP_VELOCITY = 200;    /**     * 屏幕宽度值。     */    private int screenWidth;    /**     * 左侧布局最多可以滑动到的左边缘。值由左侧布局的宽度来定,marginLeft到达此值之后,不能再减少。     */    private int leftEdge;    /**     * 左侧布局最多可以滑动到的右边缘。值恒为0,即marginLeft到达0之后,不能增加。     */    private int rightEdge = 0;    /**     * 左侧布局完全显示时,留给右侧布局的宽度值。     */    private int leftLayoutPadding = 80;    /**     * 记录手指按下时的横坐标。     */    private float xDown;    /**     * 记录手指移动时的横坐标。     */    private float xMove;    /**     * 记录手机抬起时的横坐标。     */    private float xUp;    /**     * 左侧布局当前是显示还是隐藏。只有完全显示或隐藏时才会更改此值,滑动过程中此值无效。     */    private boolean isLeftLayoutVisible;    /**     * 左侧布局对象。     */    private View leftLayout;    /**     * 右侧布局对象。     */    private View rightLayout;    /**     * 用于监听侧滑事件的View。     */    private View mBindView;    /**     * 左侧布局的参数,通过此参数来重新确定左侧布局的宽度,以及更改leftMargin的值。     */    private MarginLayoutParams leftLayoutParams;    /**     * 右侧布局的参数,通过此参数来重新确定右侧布局的宽度。     */    private MarginLayoutParams rightLayoutParams;    /**     * 用于计算手指滑动的速度。     */    private VelocityTracker mVelocityTracker;    /**     * 重写SlidingLayout的构造函数,其中获取了屏幕的宽度。     *     * @param context     * @param attrs     */    public SlidingLayout1(Context context, AttributeSet attrs) {        super(context, attrs);        WindowManager wm = (WindowManager) context                .getSystemService(Context.WINDOW_SERVICE);        Display display = wm.getDefaultDisplay();        DisplayMetrics metrics = new DisplayMetrics();        display.getMetrics(metrics);        // 获得屏幕宽和高        screenWidth = metrics.widthPixels;        // screenWidth = wm.getDefaultDisplay().getWidth();    }    /**     * 绑定监听侧滑事件的View,即在绑定的View进行滑动才可以显示和隐藏左侧布局。     *     * @param bindView 需要绑定的View对象。     */    public void setScrollEvent(View bindView) {        mBindView = bindView;        mBindView.setOnTouchListener(new OnTouchListener() {            @Override            public boolean onTouch(View v, MotionEvent event) {                createVelocityTracker(event);                switch (event.getAction()) {                    case MotionEvent.ACTION_DOWN:                        // 手指按下时,记录按下时的横坐标                        xDown = event.getRawX();                        break;                    case MotionEvent.ACTION_MOVE:                        // 手指移动时,对比按下时的横坐标,计算出移动的距离,来调整左侧布局的leftMargin值,从而显示和隐藏左侧布局                        xMove = event.getRawX();                        int distanceX = (int) (xMove - xDown);                        if (isLeftLayoutVisible) {                            leftLayoutParams.leftMargin = distanceX;                        } else {                            leftLayoutParams.leftMargin = leftEdge + distanceX;                        }                        if (leftLayoutParams.leftMargin < leftEdge) {                            leftLayoutParams.leftMargin = leftEdge;                        } else if (leftLayoutParams.leftMargin > rightEdge) {                            leftLayoutParams.leftMargin = rightEdge;                        }                        leftLayout.setLayoutParams(leftLayoutParams);                        break;                    case MotionEvent.ACTION_UP:                        // 手指抬起时,进行判断当前手势的意图,从而决定是滚动到左侧布局,还是滚动到右侧布局                        xUp = event.getRawX();                        if (wantToShowLeftLayout()) {                            if (shouldScrollToLeftLayout()) {                                scrollToLeftLayout();                            } else {                                scrollToRightLayout();                            }                        } else if (wantToShowRightLayout()) {                            if (shouldScrollToContent()) {                                scrollToRightLayout();                            } else {                                scrollToLeftLayout();                            }                        }                        recycleVelocityTracker();                        break;                }                return isBindBasicLayout();            }        });    }    /**     * 将屏幕滚动到左侧布局界面,滚动速度设定为30.     */    public void scrollToLeftLayout() {        new ScrollTask().execute(30);    }    /**     * 将屏幕滚动到右侧布局界面,滚动速度设定为-30.     */    public void scrollToRightLayout() {        new ScrollTask().execute(-30);    }    /**     * 左侧布局是否完全显示出来,或完全隐藏,滑动过程中此值无效。     *     * @return 左侧布局完全显示返回true,完全隐藏返回false。     */    public boolean isLeftLayoutVisible() {        return isLeftLayoutVisible;    }    /**     * 在onLayout中重新设定左侧布局和右侧布局的参数。     */    @Override    protected void onLayout(boolean changed, int l, int t, int r, int b) {        super.onLayout(changed, l, t, r, b);        if (changed) {            // 获取左侧布局对象            leftLayout = getChildAt(0);            leftLayoutParams = (MarginLayoutParams) leftLayout                    .getLayoutParams();            // 重置左侧布局对象的宽度为屏幕宽度减去leftLayoutPadding            leftLayoutParams.width = screenWidth - leftLayoutPadding;            // 设置最左边距为负的左侧布局的宽度            leftEdge = -leftLayoutParams.width;            leftLayoutParams.leftMargin = leftEdge;            leftLayout.setLayoutParams(leftLayoutParams);            // 获取右侧布局对象            rightLayout = getChildAt(1);            rightLayoutParams = (MarginLayoutParams) rightLayout                    .getLayoutParams();            rightLayoutParams.width = screenWidth;            rightLayout.setLayoutParams(rightLayoutParams);        }    }    /**     * 判断当前手势的意图是不是想显示右侧布局。如果手指移动的距离是负数,且当前左侧布局是可见的,则认为当前手势是想要显示右侧布局。     *     * @return 当前手势想显示右侧布局返回true,否则返回false。     */    private boolean wantToShowRightLayout() {        return xUp - xDown < 0 && isLeftLayoutVisible;    }    /**     * 判断当前手势的意图是不是想显示左侧布局。如果手指移动的距离是正数,且当前左侧布局是不可见的,则认为当前手势是想要显示左侧布局。     *     * @return 当前手势想显示左侧布局返回true,否则返回false。     */    private boolean wantToShowLeftLayout() {        return xUp - xDown > 0 && !isLeftLayoutVisible;    }    /**     * 判断是否应该滚动将左侧布局展示出来。如果手指移动距离大于屏幕的1/2,或者手指移动速度大于SNAP_VELOCITY,     * 就认为应该滚动将左侧布局展示出来。     *     * @return 如果应该滚动将左侧布局展示出来返回true,否则返回false。     */    private boolean shouldScrollToLeftLayout() {        return xUp - xDown > screenWidth / 2                || getScrollVelocity() > SNAP_VELOCITY;    }    /**     * 判断是否应该滚动将右侧布局展示出来。如果手指移动距离加上leftLayoutPadding大于屏幕的1/2,     * 或者手指移动速度大于SNAP_VELOCITY, 就认为应该滚动将右侧布局展示出来。     *     * @return 如果应该滚动将右侧布局展示出来返回true,否则返回false。     */    private boolean shouldScrollToContent() {        return xDown - xUp + leftLayoutPadding > screenWidth / 2                || getScrollVelocity() > SNAP_VELOCITY;    }    /**     * 判断绑定滑动事件的View是不是一个基础layout,不支持自定义layout,只支持四种基本layout,     * AbsoluteLayout已被弃用。     *     * @return 如果绑定滑动事件的View是LinearLayout, RelativeLayout, FrameLayout,     * TableLayout之一就返回true,否则返回false。     */    private boolean isBindBasicLayout() {        if (mBindView == null) {            return false;        }        String viewName = mBindView.getClass().getName();        return viewName.equals(LinearLayout.class.getName())                || viewName.equals(RelativeLayout.class.getName())                || viewName.equals(FrameLayout.class.getName())                || viewName.equals(TableLayout.class.getName());    }    /**     * 创建VelocityTracker对象,并将触摸事件加入到VelocityTracker当中。     *     * @param event 右侧布局监听控件的滑动事件     */    private void createVelocityTracker(MotionEvent event) {        if (mVelocityTracker == null) {            mVelocityTracker = VelocityTracker.obtain();        }        mVelocityTracker.addMovement(event);    }    /**     * 获取手指在右侧布局的监听View上的滑动速度。     *     * @return 滑动速度,以每秒钟移动了多少像素值为单位。     */    private int getScrollVelocity() {        mVelocityTracker.computeCurrentVelocity(1000);        int velocity = (int) mVelocityTracker.getXVelocity();        return Math.abs(velocity);    }    /**     * 回收VelocityTracker对象。     */    private void recycleVelocityTracker() {        mVelocityTracker.recycle();        mVelocityTracker = null;    }    class ScrollTask extends AsyncTask<Integer, Integer, Integer> {        @Override        protected Integer doInBackground(Integer... speed) {            int leftMargin = leftLayoutParams.leftMargin;            // 根据传入的速度来滚动界面,当滚动到达左边界或右边界时,跳出循环。            while (true) {                leftMargin = leftMargin + speed[0];                if (leftMargin > rightEdge) {                    leftMargin = rightEdge;                    break;                }                if (leftMargin < leftEdge) {                    leftMargin = leftEdge;                    break;                }                publishProgress(leftMargin);                // 为了要有滚动效果产生,每次循环使线程睡眠20毫秒,这样肉眼才能够看到滚动动画。                try {                    Thread.sleep(20);                } catch (InterruptedException e) {                    e.printStackTrace();                }            }            if (speed[0] > 0) {                isLeftLayoutVisible = true;            } else {                isLeftLayoutVisible = false;            }            return leftMargin;        }        @Override        protected void onProgressUpdate(Integer... leftMargin) {            leftLayoutParams.leftMargin = leftMargin[0];            leftLayout.setLayoutParams(leftLayoutParams);        }        @Override        protected void onPostExecute(Integer leftMargin) {            leftLayoutParams.leftMargin = leftMargin;            leftLayout.setLayoutParams(leftLayoutParams);        }    }}
首先在onLayout()方法中分别获取到左侧菜单、右侧菜单和内容布局的参数,并将内容布局的宽度重定义成屏幕的宽度,这样就可以保证内容 布局既能覆盖住下面的菜单布局,还能偏移出屏幕。然后在onTouch()方法中监听触屏事件,以判断用户手势的意图。这里事先定义好了几种滑动状 态,DO_NOTHING表示没有进行任何滑动,SHOW_LEFT_MENU表示用户想要滑出左侧菜单,SHOW_RIGHT_MENU表示用户想要滑 出右侧菜单,HIDE_LEFT_MENU表示用户想要隐藏左侧菜单,HIDE_RIGHT_MENU表示用户想要隐藏右侧菜单,在 checkSlideState()方法中判断出用户到底是想进行哪一种滑动操作,并给slideState变量赋值,然后根据slideState的值 决定如何偏移内容布局。接着当用户手指离开屏幕时,会根据当前的滑动距离,决定后续的滚动方向,通过LeftMenuScrollTask和 RightMenuScrollTask来完成完整的滑动过程。另外在滑动的过程,内容布局上的事件会被屏蔽掉,主要是通过一系列的return操作实现。

在布局中引用
<?xml version="1.0" encoding="utf-8"?>
<com.example.demo.view.SlidingLayout2
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/slidingLayout_fragment_double"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<RelativeLayout
android:layout_width="280dip"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:background="#00ccff"
android:visibility="invisible" >

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="This is left menu"
android:textColor="#000000"
android:textSize="28sp" />
</RelativeLayout>

<RelativeLayout
android:layout_width="280dip"
android:layout_height="match_parent"
android:layout_alignParentRight="true"
android:background="#00ffcc"
android:visibility="invisible" >

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="This is right menu"
android:textColor="#000000"
android:textSize="28sp" />
</RelativeLayout>

<LinearLayout
android:id="@+id/content"
android:layout_width="320dip"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#e9e9e9" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<Button
android:id="@+id/show_left_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:text="show left"
/>
<Button
android:id="@+id/show_right_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:text="show right"
/>
</RelativeLayout>
<ListView
android:id="@+id/contentList"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:scrollbars="none"
android:cacheColorHint="#00000000" >
</ListView>
</LinearLayout>
</com.example.demo.view.SlidingLayout2>
使用了自定义的SlidingLayout2作为根布局,然后依次加入了三个子布局分别作为左侧菜单、右侧菜单和内容的布局。左侧菜单和右侧菜单中都只是简单地放入了一个TextView用于显示一段文字,内容布局中放入了一个ListView。注意要让左侧菜单和父布局左边缘对齐,右侧菜单和父布局右边缘对齐。

用法也是参照上篇的写法,我也写在了一个Fragment中:
public class DoubleMenu extends Fragment {    /**     * 双向滑动菜单布局     */    private SlidingLayout2 doubleSldingLayout;    /**     * 在内容布局上显示的ListView     */    private ListView contentList;    /**     * ListView的适配器     */    private ArrayAdapter<String> contentListAdapter;    /**     * 用于填充contentListAdapter的数据源。     */    private List<String> dataList;    @Nullable    @Override    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {        View view = inflater.inflate(R.layout.fragment_double, container, false);        doubleSldingLayout = (SlidingLayout2) view.findViewById(R.id.slidingLayout_fragment_double);        Button showLeftButton = (Button) view.findViewById(R.id.show_left_button);        Button showRightButton = (Button) view.findViewById(R.id.show_right_button);        contentList = (ListView) view.findViewById(R.id.contentList);        dataList=new ArrayList<>();        for (int i=0;i<15;i++)            dataList.add("Item "+i);        contentListAdapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1,                dataList);        contentList.setAdapter(contentListAdapter);        doubleSldingLayout.setScrollEvent(contentList);        showLeftButton.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                if (doubleSldingLayout.isLeftLayoutVisible()) {                    doubleSldingLayout.scrollToContentFromLeftMenu();                } else {                    doubleSldingLayout.initShowLeftState();                    doubleSldingLayout.scrollToLeftMenu();                }            }        });        showRightButton.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                if (doubleSldingLayout.isRightLayoutVisible()) {                    doubleSldingLayout.scrollToContentFromRightMenu();                } else {                    doubleSldingLayout.initShowRightState();                    doubleSldingLayout.scrollToRightMenu();                }            }        });        return view;    }}

看下效果:



参考:

http://blog.csdn.net/guolin_blog/article/details/8714621
http://blog.csdn.net/guolin_blog/article/details/8744400
http://blog.csdn.net/guolin_blog/article/details/9671609

0 0
原创粉丝点击