本文主要是介绍Android自定义ViewGroup(一)——带箭头的圆角矩形菜单,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
今天要做一个带箭头的圆角矩形菜单,大概长下面这个样子:
要求顶上的箭头要对准菜单锚点,菜单项按压反色,菜单背景色和按压色可配置。
最简单的做法就是让UX给个三角形的图片往上一贴,但是转念一想这样是不是太low了点,而且不同分辨率也不太好适配,干脆自定义一个ViewGroup吧!
自定义ViewGroup其实很简单,基本都是按一定的套路来的。
一、定义一个attrs.xml
就是声明一下你的这个自定义View有哪些可配置的属性,将来使用的时候可以自由配置。这里声明了7个属性,分别是:箭头宽度、箭头高度、箭头水平偏移、圆角半径、菜单背景色、阴影色、阴影厚度。
<resources><declare-styleable name="ArrowRectangleView"><attr name="arrow_width" format="dimension" /><attr name="arrow_height" format="dimension" /><attr name="arrow_offset" format="dimension" /><attr name="radius" format="dimension" /><attr name="background_color" format="color" /><attr name="shadow_color" format="color" /><attr name="shadow_thickness" format="dimension" /></declare-styleable>
</resources>
二、写一个继承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_co
这篇关于Android自定义ViewGroup(一)——带箭头的圆角矩形菜单的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!