最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
Android自定义ViewGroup(侧滑菜单)详解及简单实例
时间:2017-05-10 编辑:简简单单 来源:一聚教程网
自定义侧滑菜单的简单实现
不少APP中都有这种侧滑菜单,例如QQ这类的,比较有名开源库如slidingmenu。
有兴趣的可以去研究研究这个开源库。
这里我们将一种自己的实现方法,把学习的 东西做个记录,O(∩_∩)O!
首先看效果图:
这里我们实现的侧滑菜单,是将左侧隐藏的菜单和主面板看作一个整体来实现的,而左侧隐藏的菜单和主面板相当于是这个自定义View的子View。
首先来构造该自定义View的布局:
自定义的SlideMenuView包含两个子view,一个是menuView,另一个是mainView(主面板)。
代码如下 | 复制代码 |
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="${relativePackage}.${activityClass}"> android:id="@+id/slideMenu" android:layout_width="match_parent" android:layout_height="match_parent"> |
接着我们需要实现SlideMenuView的 java代码。
自定义VIew,需要继承某个父类,通过重写父类的某些方法来增强父类的功能。
这里我们选择继承ViewGroup,一般自定义View,需要重写onMeasure,onLayout和onDraw,正常情况下只要重写onDraw就可以了,特殊情况下,需要重写onMeasure 和onLayout。
代码如下 | 复制代码 |
packagecom.wind.view;
importandroid.content.Context; importandroid.util.AttributeSet; importandroid.util.Log; importandroid.view.MotionEvent; importandroid.view.View; importandroid.view.ViewGroup; importandroid.widget.Scroller;
publicclassSlideMenuViewextendsViewGroup {// FrameLayout { privatestaticfinalString TAG ="SlideMenuView"; privateView menuView, mainView; privateintmenuWidth =0;
privateScroller scroller;
publicSlideMenuView(Context context) { super(context); init(); }
publicSlideMenuView(Context context, AttributeSet attrs) { super(context, attrs); init(); }
privatevoidinit() { scroller =newScroller(getContext()); }
/** * 当一级的子View全部加载玩后调用,可以用于初始化子View的引用 * */ @Override protectedvoidonFinishInflate() { super.onFinishInflate(); menuView = getChildAt(0); mainView = getChildAt(1); menuWidth = menuView.getLayoutParams().width;
Log.d(TAG,"onFinishInflate() menuWidth: "+ menuWidth); }
/** * widthMeasureSpec和heightMeasureSpec是系统测量SlideMenu时传入的参数, * 这2个参数测量出的宽高能让SlideMenu充满窗体,其实是正好等于屏幕宽高 */ @Override protectedvoidonMeasure(intwidthMeasureSpec,intheightMeasureSpec) { 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 protectedvoidonLayout(booleanchanged,intl,intt,intr,intb) { 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); }
privateintdownX;
@Override publicbooleanonTouchEvent(MotionEvent event) { switch(event.getAction()) { caseMotionEvent.ACTION_DOWN: downX = (int) event.getX(); break;
caseMotionEvent.ACTION_MOVE: intmoveX = (int) event.getX(); intdeltaX = (moveX - downX); Log.e(TAG,"scrollX: "+ getScrollX());
intnewScrollX = getScrollX() - deltaX; //使得SlideMenuView不会滑动出界 if(newScrollX >0) newScrollX =0; if(newScrollX < -menuWidth) newScrollX = -menuWidth;
scrollTo(newScrollX,0); Log.e(TAG,"moveX: "+ moveX); downX = moveX; break; |
caseMotionEvent.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; }
returntrue; }
privatevoidopenMenu() { Log.d(TAG,"openMenu..."); scroller.startScroll(getScrollX(),0, -menuWidth-getScrollX(),400); invalidate(); }
privatevoidcloseMenu() { Log.d(TAG,"closeMenu..."); scroller.startScroll(getScrollX(),0,0-getScrollX(),400); invalidate(); }
/** * Scroller不主动去调用这个方法 * 而invalidate()可以掉这个方法 * invalidate->draw->computeScroll */ @Override publicvoidcomputeScroll() { super.computeScroll(); if(scroller.computeScrollOffset()){//返回true,表示动画没结束 scrollTo(scroller.getCurrX(),0); invalidate(); } } //用于在Activity中来控制菜单的状态 publicvoidswitchMenu() { if(getScrollX() ==0) { openMenu(); }else{ closeMenu(); } } } |
这里继承ViewGroup,由于子View都是利用系统的控件填充,所以不需要重写onDraw方法。
由于是继承自ViewGroup,需要实现onMeasure来测量两个子View的高度和宽度。我们还可以继承FrameLayout,则不需要实现onMeasure,因为FrameLayout已经帮我们实现onMeasure。
重写onLayout方法,重新定义自定义的位置摆放,左侧的侧滑菜单需要使其处于隐藏状态。
重写onTouch方法,通过监测Touch的Up和Down来滑动View来实现侧滑的效果。
关于平滑滚动
我们可以采用Scroller类中的startScroll来实现平滑滚动,同样我们可以使用自定义动画的方式来实现。
代码如下 | 复制代码 |
packagecom.wind.view;
importandroid.view.View; importandroid.view.animation.Animation; importandroid.view.animation.Transformation;
/** * 让指定view在一段时间内scrollTo到指定位置 * @author Administrator * */ publicclassScrollAnimationextendsAnimation{
privateView view; privateinttargetScrollX; privateintstartScrollX; privateinttotalValue;
publicScrollAnimation(View view,inttargetScrollX) { super(); this.view = view; this.targetScrollX = targetScrollX;
startScrollX = view.getScrollX(); totalValue =this.targetScrollX - startScrollX;
inttime = Math.abs(totalValue); setDuration(time); }
/** * 在指定的时间内一直执行该方法,直到动画结束 * interpolatedTime:0-1 标识动画执行的进度或者百分比 * time : 0 - 0.5 - 0.7 - 1 * value: 10 - 60 - 80 - 110 * 当前的值 = 起始值 + 总的差值*interpolatedTime */ @Override protectedvoidapplyTransformation(floatinterpolatedTime, Transformation t) { super.applyTransformation(interpolatedTime, t); intcurrentScrollX = (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 */ publicvoidscrollTo(intx,inty) { if(mScrollX != x || mScrollY != y) { intoldX = mScrollX; intoldY = 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 */ publicvoidscrollBy(intx,inty) { scrollTo(mScrollX + x, mScrollY + y); } |
相关文章
- sora软件价格介绍 02-22
- sora官网入口地址一览 02-22
- Sora生成的视频使用教程 02-22
- 《梦幻西游》元宵灯谜线索答案大全2024 02-22
- 《原神》有朋自远方来第一天通关攻略 02-22
- 《苏醒之路》四个结局达成攻略 02-22