Android自定义属性

[size=medium]这里我自定义一个View来说明自定义属性的用法.

[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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值