读取自定义属性
通常读取自定义控件的自定义属性是在自定义控件的构造函数中用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;
那么可以在自定义控件中重写