本文和大家一起做一个带箭头的圆角矩形菜单,大概长下面这个样子:
要求顶上的箭头要对准菜单锚点,菜单项按压反色,菜单背景色和按压色可配置。
最简单的做法就是让UX给个三角形的图片往上一贴,但是转念一想这样是不是太low了点,而且不同分辨率也不太好适配,干脆自定义一个ViewGroup吧!
自定义ViewGroup其实很简单,基本都是按一定的套路来的。
一、定义一个attrs.xml
就是声明一下你的这个自定义View有哪些可配置的属性,将来使用的时候可以自由配置。这里声明了7个属性,分别是:箭头宽度、箭头高度、箭头水平偏移、圆角半径、菜单背景色、阴影色、阴影厚度。
二、写一个继承ViewGroup的类,在构造函数中初始化这些属性
这里需要用到一个obtainStyledAttributes()方法,获取一个TypedArray对象,然后就可以根据类型获取相应的属性值了。需要注意的是该对象用完以后需要显式调用recycle()方法释放掉。
public class ArrowRectangleView extends ViewGroup {
... ...
public ArrowRectangleView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
TypedArray a = context.getTheme().obtainStyledAttributes(attrs,
R.styleable.ArrowRectangleView, defStyleAttr, 0);
for (int i = 0; i < a.getIndexCount(); i++) {
int attr = a.getIndex(i);
switch (attr) {
case R.styleable.ArrowRectangleView_arrow_width:
mArrowWidth = a.getDimensionPixelSize(attr, mArrowWidth);
break;
case R.styleable.ArrowRectangleView_arrow_height:
mArrowHeight = a.getDimensionPixelSize(attr, mArrowHeight);
break;
case R.styleable.ArrowRectangleView_radius:
mRadius = a.getDimensionPixelSize(attr, mRadius);
break;
case R.styleable.ArrowRectangleView_background_color:
mBackgroundColor = a.getColor(attr, mBackgroundColor);
break;
case R.styleable.ArrowRectangleView_arrow_offset:
mArrowOffset = a.getDimensionPixelSize(attr, mArrowOffset);
break;
case R.styleable.ArrowRectangleView_shadow_color:
mShadowColor = a.getColor(attr, mShadowColor)