android自定义ViewGroup(侧滑菜单)

自定义侧滑菜单的简单实现

不少APP中都有这种侧滑菜单,例如QQ这类的,比较有名开源库如slidingmenu。
有兴趣的可以去研究研究这个开源库。

这里我们将一种自己的实现方法,把学习的 东西做个记录,O(∩_∩)O!

首先看效果图:

image

这里我们实现的侧滑菜单,是将左侧隐藏的菜单和主面板看作一个整体来实现的,而左侧隐藏的菜单和主面板相当于是这个自定义View的子View。

首先来构造该自定义View的布局:

自定义的SlideMenuView包含两个子view,一个是menuView,另一个是mainView(主面板)。

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="${relativePackage}.${activityClass}" >

    <com.wind.view.SlideMenuView
        android:id="@+id/slideMenu"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >

        <include layout="@layout/layout_menu"/>

        <include layout="@layout/layout_main"/>
    </com.wind.view.SlideMenuView>

</RelativeLayout>

接着我们需要实现SlideMenuView的 java代码。

自定义VIew,需要继承某个父类,通过重写父类的某些方法来增强父类的功能。
这里我们选择继承ViewGroup,一般自定义View,需要重写onMeasure,onLayout和onDraw,正常情况下只要重写onDraw就可以了,特殊情况下,需要重写onMeasure 和onLayout。

package com.wind.view;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Scroller;

public class SlideMenuView extends ViewGroup { // FrameLayout {
    private static final String TAG = "SlideMenuView";
    private View menuView, mainView;
    private int menuWidth = 0;

    private Scroller scroller;

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

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

    private void init() {
        scroller = new Scroller(getContext());
    }

    /**
     * 当一级的子View全部加载玩后调用,可以用于初始化子View的引用 
     * 
     */
    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        menuView = getChildAt(0);
        mainView = getChildAt(1);
        menuWidth = menuView.getLayoutParams().width;

        Log.d(TAG, "onFinishInflate() menuWidth: " + menuWidth);
    }

        /**
         * widthMeasureSpec和heightMeasureSpec是系统测量SlideMenu时传入的参数,
         * 这2个参数测量出的宽高能让SlideMenu充满窗体,其实是正好等于屏幕宽高
         */
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        Log.d(TAG, "onMeasure: widthMeasureSpec: " + widthMeasureSpec
                + "heightMeasureSpec: " + heightMeasureSpec);

        // int measureSpec = MeasureSpec.makeMeasureSpec(menuWidth,
        // MeasureSpec.EXACTLY);
        //
        // Log.d(TAG,"onMeasure: measureSpec: " +measureSpec);
        // 测量所有子view的宽高
        // 通过getLayoutParams方法可以获取到布局文件中指定宽高
        menuView.measure(widthMeasureSpec, heightMeasureSpec);
        // 直接使用SlideMenu的测量参数,因为它的宽高都是充满父窗体
        mainView.measure(widthMeasureSpec, heightMeasureSpec);

    }

         /**
         * 重新摆放子View的位置
         * l: 当前子view的左边在父view的坐标系中的x坐标
         * t: 当前子view的顶边在父view的坐标系中的y坐标
         */
    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        Log.d(TAG, "onLayout() changed: " + changed + "l: " + l + "t: " + t
                + "r: " + r + "b: " + b);
        Log.d(TAG,"menuView.getMeasuredHeight(): " + menuView.getMeasuredHeight());
        menuView.layout(-menuWidth, 0, 0, menuView.getMeasuredHeight());
        mainView.layout(0, 0, r, b);
    }



    private int downX;

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
            downX = (int) event.getX();
            break;

        case MotionEvent.ACTION_MOVE:
            int moveX = (int) event.getX();
            int deltaX = (moveX - downX);
            Log.e(TAG, "scrollX: " + getScrollX());

            int newScrollX = getScrollX() - deltaX;
            //使得SlideMenuView不会滑动出界
            if(newScrollX > 0) newScrollX = 0;
            if(newScrollX < -menuWidth) newScrollX = -menuWidth;

            scrollTo(newScrollX, 0);
            Log.e(TAG, "moveX: " + moveX);
            downX = moveX;
            break;

        case MotionEvent.ACTION_UP:

            //①.使用自定义动画
//          ScrollAnimation scrollAnimation;
//          if(getScrollX()>-menuWidth/2){
//              //关闭菜单
////                scrollTo(0, 0);
//              scrollAnimation = new ScrollAnimation(this, 0);
//          }else {
//              //打开菜单
////                scrollTo(-menuWidth, 0);
//              scrollAnimation = new ScrollAnimation(this, -menuWidth);
//          }
//          startAnimation(scrollAnimation);


            //②使用Scroller
            if(getScrollX()>-menuWidth/2){
//              //关闭菜单
                closeMenu();
            }else {
                //打开菜单
                openMenu();
            }
            break;
        }

        return true;
    }

    private void openMenu() {
        Log.d(TAG, "openMenu...");
        scroller.startScroll(getScrollX(), 0, -menuWidth-getScrollX(), 400);
        invalidate();
    }

    private void closeMenu() {
        Log.d(TAG, "closeMenu...");
        scroller.startScroll(getScrollX(), 0, 0-getScrollX(), 400);
        invalidate();
    }

        /**
         * Scroller不主动去调用这个方法
         * 而invalidate()可以掉这个方法
         * invalidate->draw->computeScroll
         */
    @Override
    public void computeScroll() {
        super.computeScroll();
        if(scroller.computeScrollOffset()){//返回true,表示动画没结束
            scrollTo(scroller.getCurrX(), 0);
            invalidate();
        }
    }
    //用于在Activity中来控制菜单的状态
    public void switchMenu() {
        if(getScrollX() == 0) {
            openMenu();
        } else {
            closeMenu();
        }
    }
}
  • 这里继承ViewGroup,由于子View都是利用系统的控件填充,所以不需要重写onDraw方法。
  • 由于是继承自ViewGroup,需要实现onMeasure来测量两个子View的高度和宽度。我们还可以继承FrameLayout,则不需要实现onMeasure,因为FrameLayout已经帮我们实现onMeasure。
  • 重写onLayout方法,重新定义自定义的位置摆放,左侧的侧滑菜单需要使其处于隐藏状态。
  • 重写onTouch方法,通过监测Touch的Up和Down来滑动View来实现侧滑的效果。

关于平滑滚动

我们可以采用Scroller类中的startScroll来实现平滑滚动,同样我们可以使用自定义动画的方式来实现。

package com.wind.view;

import android.view.View;
import android.view.animation.Animation;
import android.view.animation.Transformation;

/**
 * 让指定view在一段时间内scrollTo到指定位置
 * @author Administrator
 *
 */
public class ScrollAnimation extends Animation{

    private View view;
    private int targetScrollX;
    private int startScrollX;
    private int totalValue;

    public ScrollAnimation(View view, int targetScrollX) {
        super();
        this.view = view;
        this.targetScrollX = targetScrollX;

        startScrollX = view.getScrollX();
        totalValue = this.targetScrollX - startScrollX;

        int time = Math.abs(totalValue);
        setDuration(time);
    }



    /**
     * 在指定的时间内一直执行该方法,直到动画结束
     * interpolatedTime:0-1  标识动画执行的进度或者百分比
     * time :  0   - 0.5  - 0.7  -   1
     * value:  10  -  60  -  80  -  110
     * 当前的值 = 起始值 + 总的差值*interpolatedTime
     */
    @Override
    protected void applyTransformation(float interpolatedTime,
            Transformation t) {
        super.applyTransformation(interpolatedTime, t);
        int currentScrollX = (int) (startScrollX + totalValue*interpolatedTime);
        view.scrollTo(currentScrollX, 0);
    }
}

如上面的代码:
通过自定义动画来让View在一段时间内重复执行这个动作。

关于getScrollX

将View向右移动的时候,通过View.getScrollX得到的值是负的。
其实可以这样理解:
*getScrollX()表示的是当前的屏幕x坐标的最小值-移动的距离(向右滑动时移动的距离为正值,
向左滑动时移动的距离为负值)。*

对scrollTo和scrollBy的理解

我们查看View的源码发现,scrollBy其实调用的就是scrollTo,scrollTo就是把View移动到屏幕的X和Y位置,也就是绝对位置。而scrollBy其实就是调用的scrollTo,但是参数是当前mScrollX和mScrollY加上X和Y的位置,所以ScrollBy调用的是相对于mScrollX和mScrollY的位置。

我们在上面的代码中可以看到当我们手指不放移动屏幕时,就会调用scrollBy来移动一段相对的距离。而当我们手指松开后,会调用mScroller.startScroll(mUnboundedScrollX, 0, delta, 0, duration);来产生一段动画来移动到相应的页面,在这个过程中系统回不断调用computeScroll(),我们再使用scrollTo来把View移动到当前Scroller所在的绝对位置。

/**
     * Set the scrolled position of your view. This will cause a call to
     * {@link #onScrollChanged(int, int, int, int)} and the view will be
     * invalidated.
     * @param x the x position to scroll to
     * @param y the y position to scroll to
     */
    public void scrollTo(int x, int y) {
        if (mScrollX != x || mScrollY != y) {
            int oldX = mScrollX;
            int oldY = mScrollY;
            mScrollX = x;
            mScrollY = y;
            invalidateParentCaches();
            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
            if (!awakenScrollBars()) {
                invalidate(true);
            }
        }
    }
   /**
     * Move the scrolled position of your view. This will cause a call to
     * {@link #onScrollChanged(int, int, int, int)} and the view will be
     * invalidated.
     * @param x the amount of pixels to scroll by horizontally
     * @param y the amount of pixels to scroll by vertically
     */
    public void scrollBy(int x, int y) {
        scrollTo(mScrollX + x, mScrollY + y);
    }

以上仅是个人学习的记录。

posted @ 2016-11-27 22:14  凌风天涯  阅读(211)  评论(0编辑  收藏  举报