Android读取系统控件的自定义属性

读取自定义属性通常读取自定义控件的自定义属性是在自定义控件的构造函数中用context的obtainStyledAttributes方法获取TpyeArray对象,通过TpyeArray对象获取个自定义属性,最后别忘了recycle()。attrs.xml 自定义控件public MyViewGroup(Conte
摘要由CSDN通过智能技术生成

读取自定义属性

通常读取自定义控件的自定义属性是在自定义控件的构造函数中用context的obtainStyledAttributes方法获取TpyeArray对象,通过TpyeArray对象获取个自定义属性,最后别忘了recycle()。

attrs.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="MyViewGroup" >
        <attr name="x_in" format="float"/>
        <attr name="y_in" format="float"/>

    </declare-styleable>
</resources>
自定义控件
public MyViewGroup(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray array=context.obtainStyledAttributes(attrs,R.styleable.MyViewGroup);
        x_in=array.getFloat(R.styleable.MyViewGroup_x_in,0);
        y_in=array.getFloat(R.styleable.MyViewGroup_y_in,0);
        array.recycle();
    }

当系统控件中带有自定义属性如何读取?

<ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@mipmap/ic_launcher"
            vg:x_in="0.2"
            vg:y_in="0.3"
            />

方法一:利用LayoutParams

当自定义控件是ViewGroup的子控件时且带有自定义属性的系统控件是其内,如下布局

 <com.znvoid.blogs.MyViewGroup
        android:id="@+id/myview"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@mipmap/ic_launcher"
            vg:x_in="0.2"
            vg:y_in="0.3"
            />
    </com.znvoid.blogs.MyViewGroup>

首先了解下generateLayoutParams()方法,为父容器生成 子view 的布局LayoutParams在Layoutinflater.rInflate()中被调用

public LayoutParams generateLayoutParams(AttributeSet attrs) {
    return new LayoutParams(getContext(), attrs);
}

如果一个View想要被添加到这个容器中,这个view可以调用此方法生成和容器类匹配的布局LayoutParams;

那么可以在自定义控件中重写

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值