自定义控件时时常使用到自定义属性的操作:
一、在res/values下自定义attrs.xml文件:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="MyViewAttr">
<attr name="my_text" format="string"></attr>
<attr name="my_background" format="reference|color"/>
<attr name="my_height" format="dimension"/>
<attr name="my_textSize" format="dimension" />
<attr name="my_textColor" format="reference|color"/>
<attr name="my_enum">
<enum name="match_parent" value="-1"/>
<enum name="wrap_content" value="-2"/>
</attr>
<attr name="my_linenums" format="integer"/>
</declare-styleable>
</resources>
自定义的属性类型常用的有:string,integer,dimension,reference,color,enum;
像背景这种既可以是颜色属性(color),也可以是引用属性(reference),中间使用"|"来隔开
二、在layout文件中使用:
其中:<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:myview="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <navigation.learn.com.learnproject.myView android:id="@+id/myTestView" android:layout_width="wrap_content" android:layout_height="wrap_content" myview:my_text="@string/app_name" myview:my_textSize="20sp" myview:my_height="30dp" myview:my_background="@mipmap/contacts_icon1" myview:my_textColor="@color/colorAccent" myview:my_enum="match_parent" myview:my_linenums="5" /> </LinearLayout>
myview为自定义的属性命名空间名,其后的命名空间在Android Studio中定义为xmlns:myview="http://schemas.android.com/apk/res-auto"
即可;在Eclipse指定为"http://schemas.android.com/apk/res-auto"
定义完命名空间后,即可使用自定义的属性;"http://schemas.android.com/apk/res/(工程所在的包名)"
三、代码中获取自定义命名属性的值:
public class myView extends View{
public myView(Context context) {
super(context);
}
public myView(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.MyViewAttr);
String my_text = typedArray.getString(R.styleable.MyViewAttr_my_text);
float my_textSize = typedArray.getDimension(R.styleable.MyViewAttr_my_textSize, 20);
float my_height = typedArray.getDimension(R.styleable.MyViewAttr_my_height, 30);
Drawable my_background = typedArray.getDrawable(R.styleable.MyViewAttr_my_background);
int my_textColor = typedArray.getColor(R.styleable.MyViewAttr_my_textColor, 0);
int my_linenums = typedArray.getInteger(R.styleable.MyViewAttr_my_linenums, 5);
typedArray.recycle();
}
public myView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
}
使用TypedArray来根据相应的数据类型来获取,继而在尔后的自定义View中进行参数设置。
最后一定要注意TypedArray使用完后调用recycle进行回收。