Android 自定义view 中增加属性,初始化时读取

因为自定义View 有正向和反向两个状态,所以需要在初始化时区分加载哪个layout

在Android中,要在自定义View中增加属性,你需要完成以下步骤:

  1. 在res/values/attrs.xml文件中定义属性。

  2. 在自定义View的构造函数中获取这些属性。

  3. 在布局文件中使用这些属性。

attrs.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="SeriseViewState">
        <attr name="overturn" format="string" />
    </declare-styleable>
</resources>

自定义VIEW 中获取属性

constructor(context: Context) : super(context) {
        init(context, null)
}

constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
        init(context, attrs)
}

private fun init(context: Context, attrs: AttributeSet?) {
    
        // 正向view
        var layout = R.layout.item_aaa
        if (attrs != null) {
            val a: TypedArray = context.obtainStyledAttributes(attrs,R.styleable.SeriseViewState)
            val text = a?.getString(R.styleable.SeriseViewState_overturn)
            if (!TextUtils.isEmpty(text) && text.equals("1")) {
                // 设置反向
                layout = R.layout.item_bbb
            }
        }

        val view: View = LayoutInflater.from(context).inflate(layout, this)
}

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值