android 参数 attrs.xml,使用attrs.xml自定义属性

控件有很多属性,如android:id、android:layout_width、android:layout_height等,但是这些属性都是系统自带的属性。使用attrs.xml文件,可以自己定义属性。本文在Android自定义控件的基础上,用attrs.xml文件自己定义了属性。

首先,在values文件夹下,新建一个attrs.xml文件,文件内容如下:

其中,表明样式名称为CustomView,下面包含了两个自定义属性tColor和tSize,其中tColor是颜色(color)类的属性,tSize是尺寸(dimension)类的属性。

主窗体的布局文件如下:

xmlns:tools="http://schemas.android.com/tools"

xmlns:test="http://schemas.android.com/apk/res/com.hzhi.customview"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:paddingBottom="@dimen/activity_vertical_margin"

android:paddingLeft="@dimen/activity_horizontal_margin"

android:paddingRight="@dimen/activity_horizontal_margin"

android:paddingTop="@dimen/activity_vertical_margin"

tools:context=".MainActivity" >

android:id="@+id/cusView"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

test:tColor="#00FFFF"

test:tSize="30dp"

>

定义了xmlns:test="http://schemas.android.com/apk/res/com.hzhi.customview"(其中com.hzhi.customview是包名),在控件属性中就可以增加test:tColor和test:tSize两个属性。

CustomView.java的构造函数:

// 构造函数

public CustomView(Context context, AttributeSet attrs) {

super(context, attrs);

// 获得TypedArray

TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CustomView);

// 获得attrs.xml里面的属性值,格式为:名称_属性名,后面是默认值

int tColor = a.getColor(R.styleable.CustomView_tColor, Color.GREEN);

float tSize = a.getDimension(R.styleable.CustomView_tSize, 35);

p.setColor(tColor);

p.setTextSize(tSize);

// 返回一个绑定资源结束的信号给资源

a.recycle();

}

首先从R.styleable.CustomView获得了TypedArray变量,再用getColor(),getDimension()等方法获取相应的属性值,属性格式为“样式名_属性名”,属性后面的参数是默认值。获得属性值以后,就可以应用这些属性值。recycle()方法用于返回信号给资源(不懂什么意思)。

运行结果如下:

d6ab820b15cff7f2d8246b6fd1eec739.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值