在布局文件中使用
<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);