码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2014-11-05 10:54:59      阅读:129      评论:0      收藏:0      [点我收藏+]

标签:自定义属性

有时候我们自定义的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" 为使用

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

使用my:XXX时并不会验证属性的正确性。

但是在自定义view代码中获取属性值的时候会进行验证。

获取属性值对自定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 获取获取对应的属性值了。

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


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

标签:自定义属性

原文地址:http://blog.csdn.net/superharder/article/details/40818019

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!