也是项目要求,需要做个横向选择的控件,然而从来没有写过自定义控件的我当时是一脸懵逼,哈哈哈,所以说自己还是进步了呢。
横向选择控件就是这样子的:
当选择其中一个选项时,该选项为蓝色。选项个数,默认被选项可根据需求,在使用时设置。
首先是定义控件的属性:
需要先在res/values目录下新建aatrs.xml文件,然后声明属性:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="HorizontalSelector">
<attr name="textSize" format="dimension"/>
<attr name="backgroundSelector" format="reference"/>
<attr name="textColorSelector" format="reference"/>
<attr name="itemHeight" format="dimension"/>
<attr name="itemWidth" format="dimension"/>
<attr name="itemMargin" format="dimension"/>
</declare-styleable>
</resources>
给需要的属性命名为HorizontalSelector,它包括了6种属性,name为属性名称,format为格式,它有10种类别:reference-资源id,color,boolean,dimension-尺寸,float,integer,string,fraction-百分数,enum,flag。
属性声明完之后,可以在layout和stylte中使用他们。
在三个构造函数中,获取属性值:
// 获取屏幕密度
private final float density = getContext().getResources().getDisplayMetrics().density;
// 设置样式属性的默认值
private int backgroundSelector = R.drawable.horizontal_selector_background; // 背景
private int colorSelector = R.color.horizontal_selector_tv; // 文本颜色
private int textSize = 18; // 字体大小
private int itemHeight = ViewGroup.LayoutParams.WRAP_CONTENT; // 高度
private int itemWidth = ViewGroup.LayoutParams.WRAP_CONTENT; // 宽度
private int itemMargin = 20; // 间距
// 被选择的子元素的位置
private int selectedIndex = 0;
private List<SelectorItem> items = new ArrayList<>();
OnSelectionChangeListener changeListener;
public HorizontalSelector(Context context) {
this(context, null);
}
public HorizontalSelector(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public HorizontalSelector(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs