自定义控件之横向选择控件

也是项目要求,需要做个横向选择的控件,然而从来没有写过自定义控件的我当时是一脸懵逼,哈哈哈,所以说自己还是进步了呢。

横向选择控件就是这样子的:
这里写图片描述

当选择其中一个选项时,该选项为蓝色。选项个数,默认被选项可根据需求,在使用时设置。

首先是定义控件的属性:
需要先在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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值