版权声明:本文为博主原创文章,未经博主容许不得转载php
系列教程:Android开发之从零开始系列java
源码:AnliaLee/ExpandMenu,欢迎starandroid
你们要是看到有错误的地方或者有啥好的建议,欢迎留言评论git
前言:最近项目里要实现一个 可展开收起的水平菜单栏控件,刚接到需求时想着用自定义View本身来绘制,发现要实现 圆角、阴影、菜单滑动等效果很是复杂且耗时间。好在这些效果 Android原生代码中都已经有很是成熟的解决方案,咱们只须要去继承它们进行 二次开发就行。本期将教你们如何 继承ViewGroup(RelativeLayout)实现自定义菜单栏github
本篇只着重于思路和实现步骤,里面用到的一些知识原理不会很是细地拿来说,若是有不清楚的api或方法能够在网上搜下相应的资料,确定有大神讲得很是清楚的,我这就不献丑了。本着认真负责的精神我会把相关知识的博文连接也贴出来(其实就是懒不想写那么多哈哈),你们能够自行传送。为了照顾第一次阅读系列博客的小伙伴,本篇会出现一些在以前系列博客就讲过的内容,看过的童鞋自行跳过该段便可canvas
国际惯例,先上效果图api
自定义ViewGroup和自定义View的绘制过程有所不一样,View能够直接在本身的onDraw方法中绘制所须要的效果,而ViewGroup会先测量子View的大小位置(onLayout),而后再进行绘制,若是子View或background为空,则不会调用draw方法绘制。固然咱们能够调用setWillNotDraw(false)让ViewGroup能够在子View或background为空的状况下进行绘制,但咱们会为ViewGroup设置一个默认背景,因此能够省去这句代码app
设置背景很简单,由于要实现圆角、描边等效果,因此咱们选择使用GradientDrawable来定制背景,而后调用setBackground方法设置背景。建立HorizontalExpandMenu,继承自RelativeLayout,同时自定义Attrs属性ide
public class HorizontalExpandMenu extends RelativeLayout {
private Context mContext;
private AttributeSet mAttrs;
private int defaultWidth;//默认宽度
private int defaultHeight;//默认长度
private int viewWidth;
private int viewHeight;
private int menuBackColor;//菜单栏背景色
private float menuStrokeSize;//菜单栏边框线的size
private int menuStrokeColor;//菜单栏边框线的颜色
private float menuCornerRadius;//菜单栏圆角半径
public HorizontalExpandMenu(Context context) {
super(context);
this.mContext = context;
init();
}
public HorizontalExpandMenu(Context context, AttributeSet attrs) {
super(context, attrs);
this.mContext = context;
this.mAttrs = attrs;
init();
}
private void init(){
TypedArray typedArray = mContext.obtainStyledAttributes(mAttrs, R.styleable.HorizontalExpandMenu);
defaultWidth = DpOrPxUtils.dip2px(mContext,200);
defaultHeight = DpOrPxUtils.dip2px(mContext,40);
menuBackColor = typedArray.getColor(R.styleable.HorizontalExpandMenu_back_color,Color.WHITE);
menuStrokeSize = typedArray.getDimension(R.styleable.HorizontalExpandMenu_stroke_size,1);
menuStrokeColor = typedArray.getColor(R.styleable.HorizontalExpandMenu_stroke_color,Color.GRAY);
menuCornerRadius = typedArray.getDimension(R.styleable.HorizontalExpandMenu_corner_radius,DpOrPxUtils.dip2px(mContext,20));
typedArray.recycle();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int height = measureSize(defaultHeight, heightMeasureSpec);
int width = measureSize(defaultWidth, widthMeasureSpec);
viewHeight = height;
viewWidth = width;
setMeasuredDimension(viewWidth,viewHeight);
//布局代码中若是没有设置background属性则在此处添加一个背景
if(getBackground()==null){
setMenuBackground();
}
}
private int measureSize(int defaultSize, int measureSpec) {
int result = defaultSize;
int specMode = View.MeasureSpec.getMode(measureSpec);
int specSize = View.MeasureSpec.getSize(measureSpec);
if (specMode == View.MeasureSpec.EXACTLY) {
result = specSize;
} else if (specMode == View.MeasureSpec.AT_MOST) {
result = Math.min(result, specSize);
}
return result;
}
/** * 设置菜单背景,若是要显示阴影,需在onLayout以前调用 */
private void setMenuBackground(){
GradientDrawable gd = new GradientDrawable();
gd.setColor(menuBackColor);
gd.setStroke((int)menuStrokeSize, menuStrokeColor);
gd.setCornerRadius(menuCornerRadius);
setBackground(gd);
}
}
复制代码
attrs属性布局
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!--注意这里的name要和自定义View的名称一致,否则在xml布局中没法引用-->
<declare-styleable name="HorizontalExpandMenu">
<attr name="back_color" format="color"></attr>
<attr name="stroke_size" format="dimension"></attr>
<attr name="stroke_color" format="color"></attr>
<attr name="corner_radius" format="dimension"></attr>
</declare-styleable>
</resources>
复制代码
在布局文件中使用
<com.anlia.expandmenu.widget.HorizontalExpandMenu android:id="@+id/expandMenu1" android:layout_width="match_parent" android:layout_height="40dp" android:layout_alignParentBottom="true" android:layout_marginBottom="20dp" android:layout_marginLeft="15dp" android:layout_marginRight="15dp">
</com.anlia.expandmenu.widget.HorizontalExpandMenu>
复制代码
效果如图
咱们要绘制菜单栏两边的按钮,首先是要为按钮圈地(测量位置和大小)。设置按钮区域为正方形,位于左侧或右侧(根据开发者设置而定),边长和菜单栏ViewGroup的高相等。按钮中的加号可使用Path进行绘制(固然也能够用矢量图或位图),代码以下
public class HorizontalExpandMenu extends RelativeLayout {
//省略部分代码...
private float buttonIconDegrees;//按钮icon符号竖线的旋转角度
private float buttonIconSize;//按钮icon符号的大小
private float buttonIconStrokeWidth;//按钮icon符号的粗细
private int buttonIconColor;//按钮icon颜色
private int buttonStyle;//按钮类型
private int buttonRadius;//按钮矩形区域内圆半径
private float buttonTop;//按钮矩形区域top值
private float buttonBottom;//按钮矩形区域bottom值
private Point rightButtonCenter;//右按钮中点
private float rightButtonLeft;//右按钮矩形区域left值
private float rightButtonRight;//右按钮矩形区域right值
private Point leftButtonCenter;//左按钮中点
private float leftButtonLeft;//左按钮矩形区域left值
private float leftButtonRight;//左按钮矩形区域right值
/** * 根按钮所在位置,默认为右边 */
public class ButtonStyle {
public static final int Right = 0;
public static final int Left = 1;
}
private void init(){
//省略部分代码...
buttonStyle = typedArray.getInteger(R.styleable.HorizontalExpandMenu_button_style,ButtonStyle.Right);
buttonIconDegrees = 0;
buttonIconSize = typedArray.getDimension(R.styleable.HorizontalExpandMenu_button_icon_size,DpOrPxUtils.dip2px(mContext,8));
buttonIconStrokeWidth = typedArray.getDimension(R.styleable.HorizontalExpandMenu_button_icon_stroke_width,8);
buttonIconColor = typedArray.getColor(R.styleable.HorizontalExpandMenu_button_icon_color,Color.GRAY);
buttonIconPaint = new Paint();
buttonIconPaint.setColor(buttonIconColor);
buttonIconPaint.setStyle(Paint.Style.STROKE);
buttonIconPaint.setStrokeWidth(buttonIconStrokeWidth);
buttonIconPaint.setAntiAlias(true);
path = new Path();
leftButtonCenter = new Point();
rightButtonCenter = new Point();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int height = measureSize(defaultHeight, heightMeasureSpec);
int width = measureSize(defaultWidth, widthMeasureSpec);
viewHeight = height;
viewWidth = width;
setMeasuredDimension(viewWidth,viewHeight);
buttonRadius = viewHeight/2;
layoutRootButton();
//布局代码中若是没有设置background属性则在此处添加一个背景
if(getBackground()==null){
setMenuBackground();
}
}
@Override
protected void onDraw(Canvas canvas) {
layoutRootButton();
if(buttonStyle == ButtonStyle.Right){
drawRightIcon(canvas);
}else {
drawLeftIcon(canvas);
}
super.onDraw(canvas);//注意父方法在最后调用,以避免icon被遮盖
}
/** * 测量按钮中点和矩形位置 */
private void layoutRootButton(){
buttonTop = 0;
buttonBottom = viewHeight;
rightButtonCenter.x = viewWidth- buttonRadius;
rightButtonCenter.y = viewHeight/2;
rightButtonLeft = rightButtonCenter.x- buttonRadius;
rightButtonRight = rightButtonCenter.x+ buttonRadius;
leftButtonCenter.x = buttonRadius;
leftButtonCenter.y = viewHeight/2;
leftButtonLeft = leftButtonCenter.x- buttonRadius;
leftButtonRight = leftButtonCenter.x+ buttonRadius;
}
/** * 绘制左边的按钮 * @param canvas */
private void drawLeftIcon(Canvas canvas){
path.reset();
path.moveTo(leftButtonCenter.x- buttonIconSize, leftButtonCenter.y);
path.lineTo(leftButtonCenter.x+ buttonIconSize, leftButtonCenter.y);
canvas.drawPath(path, buttonIconPaint);//划横线
canvas.save();
canvas.rotate(-buttonIconDegrees, leftButtonCenter.x, leftButtonCenter.y);//旋转画布,让竖线能够随角度旋转
path.reset();
path.moveTo(leftButtonCenter.x, leftButtonCenter.y- buttonIconSize);
path.lineTo(leftButtonCenter.x, leftButtonCenter.y+ buttonIconSize);
canvas.drawPath(path, buttonIconPaint);//画竖线
canvas.restore();
}
/** * 绘制右边的按钮 * @param canvas */
private void drawRightIcon(Canvas canvas){
path.reset();
path.moveTo(rightButtonCenter.x- buttonIconSize, rightButtonCenter.y);
path.lineTo(rightButtonCenter.x+ buttonIconSize, rightButtonCenter.y);
canvas.drawPath(path, buttonIconPaint);//划横线
canvas.save();
canvas.rotate(buttonIconDegrees, rightButtonCenter.x, rightButtonCenter.y);//旋转画布,让竖线能够随角度旋转
path.reset();
path.moveTo(rightButtonCenter.x, rightButtonCenter.y- buttonIconSize);
path.lineTo(rightButtonCenter.x, rightButtonCenter.y+ buttonIconSize);
canvas.drawPath(path, buttonIconPaint);//画竖线
canvas.restore();
}
}
复制代码
新增attrs属性
<declare-styleable name="HorizontalExpandMenu">
//省略部分代码...
<attr name="button_style">
<enum name="right" value="0"/>
<enum name="left" value="1"/>
</attr>
<attr name="button_icon_size" format="dimension"></attr>
<attr name="button_icon_stroke_width" format="dimension"></attr>
<attr name="button_icon_color" format="color"></attr>
</declare-styleable>
复制代码
布局文件
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent">
<LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical">
<com.anlia.expandmenu.widget.HorizontalExpandMenu android:id="@+id/expandMenu1" android:layout_width="match_parent" android:layout_height="40dp" android:layout_marginTop="20dp" android:layout_marginLeft="15dp" android:layout_marginRight="15dp">
</com.anlia.expandmenu.widget.HorizontalExpandMenu>
<com.anlia.expandmenu.widget.HorizontalExpandMenu android:id="@+id/expandMenu2" android:layout_width="match_parent" android:layout_height="40dp" android:layout_marginTop="10dp" android:layout_marginLeft="15dp" android:layout_marginRight="15dp" app:button_style="left">
</com.anlia.expandmenu.widget.HorizontalExpandMenu>
</LinearLayout>
</RelativeLayout>
复制代码
效果如图
以前咱们定义了buttonIconDegrees属性,下面咱们经过Animation的插值器增减buttonIconDegrees的数值让按钮符号能够进行变换,同时监听Touch为按钮设置点击事件
public class HorizontalExpandMenu extends RelativeLayout {
//省略部分代码...
private boolean isExpand;//菜单是否展开,默认为展开
private float downX = -1;
private float downY = -1;
private int expandAnimTime;//展开收起菜单的动画时间
private void init(){
//省略部分代码...
buttonIconDegrees = 90;//菜单初始状态为展开,因此旋转角度为90,按钮符号为 - 号
expandAnimTime = typedArray.getInteger(R.styleable.HorizontalExpandMenu_expand_time,400);
isExpand = true;
anim = new ExpandMenuAnim();
}
@Override
public boolean onTouchEvent(MotionEvent event) {
super.onTouchEvent(event);
float x = event.getX();
float y = event.getY();
switch (event.getAction()){
case MotionEvent.ACTION_DOWN:
downX = event.getX();
downY = event.getY();
break;
case MotionEvent.ACTION_MOVE:
break;
case MotionEvent.ACTION_UP:
switch (buttonStyle){
case ButtonStyle.Right:
if(x==downX&&y==downY&&y>=buttonTop&&y<=buttonBottom&&x>=rightButtonLeft&&x<=rightButtonRight){
expandMenu(expandAnimTime);
}
break;
case ButtonStyle.Left:
if(x==downX&&y==downY&&y>=buttonTop&&y<=buttonBottom&&x>=leftButtonLeft&&x<=leftButtonRight){
expandMenu(expandAnimTime);
}
break;
}
break;
}
return true;
}
private class ExpandMenuAnim extends Animation {
public ExpandMenuAnim() {}
@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
super.applyTransformation(interpolatedTime, t);
if(isExpand){//展开菜单
buttonIconDegrees = 90 * interpolatedTime;
}else {//收起菜单
buttonIconDegrees = 90 - 90 * interpolatedTime;
}
postInvalidate();
}
}
/** * 展开收起菜单 * @param time 动画时间 */
private void expandMenu(int time){
anim.setDuration(time);
isExpand = isExpand ?false:true;
this.startAnimation(anim);
}
}
复制代码
效果如图
ViewGroup的大小和位置须要用到layout()方法进行设置,和按钮动画同样,咱们使用动画插值器动态改变菜单的长度
public class HorizontalExpandMenu extends RelativeLayout {
//省略部分代码...
private float backPathWidth;//绘制子View区域宽度
private float maxBackPathWidth;//绘制子View区域最大宽度
private int menuLeft;//menu区域left值
private int menuRight;//menu区域right值
private boolean isFirstLayout;//是否第一次测量位置,主要用于初始化menuLeft和menuRight的值
private void init(){
//省略部分代码...
isFirstLayout = true;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
//省略部分代码...
maxBackPathWidth = viewWidth- buttonRadius *2;
backPathWidth = maxBackPathWidth;
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
super.onLayout(changed, l, t, r, b);
//若是子View数量为0时,onLayout后getLeft()和getRight()才能获取相应数值,menuLeft和menuRight保存menu初始的left和right值
if(isFirstLayout){
menuLeft = getLeft();
menuRight = getRight();
isFirstLayout = false;
}
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
viewWidth = w;//当menu的宽度改变时,从新给viewWidth赋值
}
@Override
public boolean onTouchEvent(MotionEvent event) {
//省略部分代码...
switch (event.getAction()){
case MotionEvent.ACTION_UP:
if(backPathWidth==maxBackPathWidth || backPathWidth==0){//动画结束时按钮才生效
switch (buttonStyle){
case ButtonStyle.Right:
if(x==downX&&y==downY&&y>=buttonTop&&y<=buttonBottom&&x>=rightButtonLeft&&x<=rightButtonRight){
expandMenu(expandAnimTime);
}
break;
case ButtonStyle.Left:
if(x==downX&&y==downY&&y>=buttonTop&&y<=buttonBottom&&x>=leftButtonLeft&&x<=leftButtonRight){
expandMenu(expandAnimTime);
}
break;
}
}
break;
}
}
private class ExpandMenuAnim extends Animation {
public ExpandMenuAnim() {}
@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
super.applyTransformation(interpolatedTime, t);
float left = menuRight - buttonRadius *2;//按钮在右边,菜单收起时按钮区域left值
float right = menuLeft + buttonRadius *2;//按钮在左边,菜单收起时按钮区域right值
if(isExpand){//打开菜单
backPathWidth = maxBackPathWidth * interpolatedTime;
buttonIconDegrees = 90 * interpolatedTime;
}else {//关闭菜单
backPathWidth = maxBackPathWidth - maxBackPathWidth * interpolatedTime;
buttonIconDegrees = 90 - 90 * interpolatedTime;
}
if(buttonStyle == ButtonStyle.Right){
layout((int)(left-backPathWidth),getTop(), menuRight,getBottom());//会调用onLayout从新测量子View位置
}else {
layout(menuLeft,getTop(),(int)(right+backPathWidth),getBottom());
}
postInvalidate();
}
}
}
复制代码
效果如图
为了菜单栏的显示效果,咱们限制其直接子View的数量为一个。在子View数量不为0的状况下,咱们须要动态显示和隐藏子View,且在onLayout()方法中测量子View的位置,修改HorizontalExpandMenu
public class HorizontalExpandMenu extends RelativeLayout {
//省略部分代码...
private boolean isAnimEnd;//动画是否结束
private View childView;
private void init(){
//省略部分代码...
isAnimEnd = false;
anim.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {}
@Override
public void onAnimationEnd(Animation animation) {
isAnimEnd = true;
}
@Override
public void onAnimationRepeat(Animation animation) {}
});
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
super.onLayout(changed, l, t, r, b);
//若是子View数量为0时,onLayout后getLeft()和getRight()才能获取相应数值,menuLeft和menuRight保存menu初始的left和right值
if(isFirstLayout){
menuLeft = getLeft();
menuRight = getRight();
isFirstLayout = false;
}
if(getChildCount()>0){
childView = getChildAt(0);
if(isExpand){
if(buttonStyle == Right){
childView.layout(leftButtonCenter.x,(int) buttonTop,(int) rightButtonLeft,(int) buttonBottom);
}else {
childView.layout((int)(leftButtonRight),(int) buttonTop,rightButtonCenter.x,(int) buttonBottom);
}
//限制子View在菜单内,LayoutParam类型和当前ViewGroup一致
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(viewWidth,viewHeight);
layoutParams.setMargins(0,0,buttonRadius *3,0);
childView.setLayoutParams(layoutParams);
}else {
childView.setVisibility(GONE);
}
}
if(getChildCount()>1){//限制直接子View的数量
throw new IllegalStateException("HorizontalExpandMenu can host only one direct child");
}
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
viewWidth = w;//当menu的宽度改变时,从新给viewWidth赋值
if(isAnimEnd){//防止出现动画结束后菜单栏位置大小测量错误的bug
if(buttonStyle == Right){
if(!isExpand){
layout((int)(menuRight - buttonRadius *2-backPathWidth),getTop(), menuRight,getBottom());
}
}else {
if(!isExpand){
layout(menuLeft,getTop(),(int)(menuLeft + buttonRadius *2+backPathWidth),getBottom());
}
}
}
}
private class ExpandMenuAnim extends Animation {
public ExpandMenuAnim() {}
@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
super.applyTransformation(interpolatedTime, t);
float left = menuRight - buttonRadius *2;//按钮在右边,菜单收起时按钮区域left值
float right = menuLeft + buttonRadius *2;//按钮在左边,菜单收起时按钮区域right值
if(childView!=null) {
childView.setVisibility(GONE);
}
if(isExpand){//打开菜单
backPathWidth = maxBackPathWidth * interpolatedTime;
buttonIconDegrees = 90 * interpolatedTime;
if(backPathWidth==maxBackPathWidth){
if(childView!=null) {
childView.setVisibility(VISIBLE);
}
}
}else {//关闭菜单
backPathWidth = maxBackPathWidth - maxBackPathWidth * interpolatedTime;
buttonIconDegrees = 90 - 90 * interpolatedTime;
}
if(buttonStyle == Right){
layout((int)(left-backPathWidth),getTop(), menuRight,getBottom());//会调用onLayout从新测量子View位置
}else {
layout(menuLeft,getTop(),(int)(right+backPathWidth),getBottom());
}
postInvalidate();
}
}
/** * 展开收起菜单 * @param time 动画时间 */
private void expandMenu(int time){
anim.setDuration(time);
isExpand = isExpand ?false:true;
this.startAnimation(anim);
isAnimEnd = false;
}
}
复制代码
布局代码
<LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical">
<com.anlia.expandmenu.widget.HorizontalExpandMenu android:id="@+id/expandMenu1" android:layout_width="match_parent" android:layout_height="40dp" android:layout_marginTop="20dp" android:layout_marginLeft="15dp" android:layout_marginRight="15dp">
<LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" android:gravity="center_vertical" android:clickable="true">
<TextView android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:gravity="center" android:text="item1"/>
<TextView android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:gravity="center" android:text="item2"/>
<TextView android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:gravity="center" android:text="item3"/>
<TextView android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:gravity="center" android:text="item4"/>
</LinearLayout>
</com.anlia.expandmenu.widget.HorizontalExpandMenu>
<com.anlia.expandmenu.widget.HorizontalExpandMenu android:id="@+id/expandMenu2" android:layout_width="match_parent" android:layout_height="40dp" android:layout_marginTop="15dp" android:layout_marginLeft="15dp" android:layout_marginRight="15dp" app:button_style="left">
<HorizontalScrollView android:layout_width="match_parent" android:layout_height="match_parent" android:fillViewport="true" android:scrollbars="none">
<LinearLayout android:layout_width="wrap_content" android:layout_height="match_parent" android:orientation="horizontal" android:gravity="center_vertical" android:clickable="true">
<TextView android:layout_width="100dp" android:layout_height="match_parent" android:gravity="center" android:background="@color/blue" android:text="item1"/>
<TextView android:layout_width="50dp" android:layout_height="match_parent" android:gravity="center" android:background="@color/yellow" android:text="item2"/>
<TextView android:layout_width="100dp" android:layout_height="match_parent" android:gravity="center" android:background="@color/green" android:text="item3"/>
<TextView android:layout_width="150dp" android:layout_height="match_parent" android:gravity="center" android:background="@color/red" android:text="item4"/>
</LinearLayout>
</HorizontalScrollView>
</com.anlia.expandmenu.widget.HorizontalExpandMenu>
</LinearLayout>
复制代码
效果如图
至此本篇教程到此结束,若是你们看了感受还不错麻烦点个赞,大家的支持是我最大的动力~