[size=medium]这里我自定义一个View来说明自定义属性的用法.
[b][color=darkred]Part 1.[/color][/b]自定义一个View:[/size]
[size=medium]这个View什么功能都没,取得自定义的两个属性的值并在日志打印出来.
在这里需要注意两点:
1.public final TypedArray obtainStyledAttributes (AttributeSet set, int[] attrs),这里第二个参数R.styleable.[color=red]MyView[/color],红字部分是自定义属性中declare-styleable标签的name属性的值.
2.可以用AttributeSet对象也就是attrs来取自定义属性的值,但是比较麻烦,推荐用TypedArray.[/size]
[size=medium][b][color=darkred]Part 2.[/color][/b]在values下建attr.xml[/size]
[size=medium]declare-styleable是可以不要的,就是说可以直接在resource标签内写attr标签,但是,还是推荐写在declare-styleable里...[/size]
[size=medium][b][color=darkred]Part 3.[/color][/b]布局页[/size]
[size=medium]注意命名空间:xmlns:[color=darkred]ray[/color]="http://schemas.android.com/apk/res-auto"
红字部分就是ray:gylAge="18"自定义控件里的部分.[/size]
[size=medium]运行结果:[/size]
[b][color=darkred]Part 1.[/color][/b]自定义一个View:[/size]
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.MyView);
Log.d("xyz","name:" + typedArray.getString(R.styleable.MyView_gylName) + "age:" + typedArray.getString(R.styleable.MyView_gylAge));
//MyView_gylName和MyView_gylAge是自定义属性,看官莫急
typedArray.recycle();
}
}
[size=medium]这个View什么功能都没,取得自定义的两个属性的值并在日志打印出来.
在这里需要注意两点:
1.public final TypedArray obtainStyledAttributes (AttributeSet set, int[] attrs),这里第二个参数R.styleable.[color=red]MyView[/color],红字部分是自定义属性中declare-styleable标签的name属性的值.
2.可以用AttributeSet对象也就是attrs来取自定义属性的值,但是比较麻烦,推荐用TypedArray.[/size]
[size=medium][b][color=darkred]Part 2.[/color][/b]在values下建attr.xml[/size]
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="MyView">
<attr name="gylName" format="string"/>
<attr name="gylAge" format="integer"/>
</declare-styleable>
</resources>
[size=medium]declare-styleable是可以不要的,就是说可以直接在resource标签内写attr标签,但是,还是推荐写在declare-styleable里...[/size]
[size=medium][b][color=darkred]Part 3.[/color][/b]布局页[/size]
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ray="http://schemas.android.com/apk/res-auto"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<com.learn.gyl.xutilssample.MyView
android:layout_width="match_parent"
android:layout_height="match_parent"
ray:gylAge="18"
ray:gylName="gyl"/>
</LinearLayout>
[size=medium]注意命名空间:xmlns:[color=darkred]ray[/color]="http://schemas.android.com/apk/res-auto"
红字部分就是ray:gylAge="18"自定义控件里的部分.[/size]
[size=medium]运行结果:[/size]
xyz: name:gylage:18