自定义view中自定义属性的用法.

有时候我们自定义的view需要用到有自己定义的属性。

首先定义自己的属性,在res/values/attrs.xml中定义,xml文件如下:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name = "myView">
        <attr name = "text" format = "string" />
        <attr name = "textSize" format = "dimension"/>
        <attr name = "textColor" format = "color"/>
        <attr name = "rectColor" format = "color"/>
    </declare-styleable>
</resources>
name属性很重要,关系到以后的调用。

format为属性的类型,这里列举了几种基本的数据类型,注意textSize等关系到大小的属性格式为dimension。


在布局文件中的使用。

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:my="http://schemas.android.com/apk/res/com.example.myview" 
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    >

    <com.example.myview.MyView 
        android:layout_width="100dp"
        android:layout_height="100dp"
        my:text = "点击开始计数"
        my:textColor = "#ffff0000"
        my:textSize = "21sp"
        my:rectColor = "#ff00ff00"
        />

</RelativeLayout>
xmlns:my="http://schemas.android.com/apk/res/com.example.myview"  为使用(建议包名改写成res-auto)

my字段调用自定义属性的关键代码。

获取属性值对自定view进行初始化。

//获取xml文件中的属性数组
	private void initAttrs(AttributeSet attrs) {
		mPanit = new Paint();
		mBound = new Rect();
		setOnClickListener(this);
		//和attr.xml中的属性列表对应上
		TypedArray ta = getContext().obtainStyledAttributes(attrs,R.styleable.myView);
		String text = ta.getString(R.styleable.myView_text);
		setText(text);
		int textSize = ta.getDimensionPixelOffset(R.styleable.myView_textSize, 26);
		setTextSize(textSize);
		int color = ta.getColor(R.styleable.myView_textColor, 0xff000000);
		setTextColor(color);
		int rectColor = ta.getColor(R.styleable.myView_rectColor, 0xff000000);
		setRectColor(rectColor);
		ta.recycle();
	}
AttributeSet attrs为xml中的属性和它所对应的值。

TypedArray ta = getContext().obtainStyledAttributes(attrs,R.styleable.myView);

只获取自定义属性名为myView中的属性。并且赋值给TypeArray ta。

之后便可根据 ta 获取获取对应的属性值了。

至于获取的属性值该怎么用,就要看你自己的了。


  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值