Android自定义属性

/ 0评 / 0

Android自定义属性的步骤

在我们自定义View的过程中,我们经常需要为自己的View添加一些自定义的属性,用来完善我们的自定义view,下面我来介绍下如何为自己的控件自定义属性。

自定义属性一般分为如下几个步骤

定义自定义属性

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!--
   使用<attr name="" format=""/>来定义属性。
   name代表标识 format代表此属性代表的格式
    -->
    <attr name="text" format="string|reference"></attr>
    <attr name="color" format="color|reference"></attr>

    <!--
    使用declare-styleable来定义属性集
    可以使用上面自定义的属性,也可以使用系统自带的属性
    -->
    <declare-styleable name="CoustomView">
        <attr name="text"></attr>
        <attr name="color"></attr>
    </declare-styleable>
</resources>

这里我只写出了基本格式,由于网上已经有人总结的很详细了,我就不再过多介绍,所有属性的定义和使用方法,请查看【Android】Android自定义属性,attr format取值类型

下面的com.jay.customattr.CoustomView是我们继承自View的自定义类,可以看到,我们在他的里面使用了jay:text和jay:color属性,其中text和color是上一步中我们自定义的属性,这里的jay指的是xmlns(xml namespace xml文件命名空间),我们在RelativeLayout里面可以看到android自带的命名空间的申明格式如下。

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

我们自己定义的属性的xmlns的定义格式为

Eclipse : xmlns:名字(本例中为jay)="http://schemas.android.com/apk/res+包名" 也就是程序的包名,在AndroidManifest.xml的package里面,直接复制过来就行。

Android Studio :  xmlns:名字(本例中为jay)="http://schemas.android.com/apk/res-auto"

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:jay="http://schemas.android.com/apk/res/com.jay.customattr"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
    <!-- com.jay.customattr.CoustomView是一个继承自View的自定义View -->
    <com.jay.customattr.CoustomView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        jay:text="自定义属性的文字"
        jay:color="#ccffff" />
</RelativeLayout>

在代码中获取属性值,需要使用TypedArray类,大致流程是,使用context.obtainStyledAttributes()获取所有属性值,然后根据属性值的id调用不同的get函数,最后TypedArray对象必须显示的回收,也就是调用recycle()方法。属性值的id为R.styleable."declare-able的name"_"attr的name",中间是一个下划线隔开。这里初始化的代码全部放在三个参数的构造函数中,然后在一个参数的里面调用两个参数的构造函数,最终调用三个参数的构造函数。

package com.jay.customattr;
import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;

public class CoustomView extends View {

	public CoustomView(Context context) {
		this(context, null);
	}

	public CoustomView(Context context, AttributeSet attrs) {
		this(context, attrs, 0);
	}

	public CoustomView(Context context, AttributeSet attrs, int defStyleAttr) {
		super(context, attrs, defStyleAttr);
		TypedArray a = context.obtainStyledAttributes(attrs,R.styleable.CoustomView, defStyleAttr, 0);
		int attrCount = a.getIndexCount();
		for (int i = 0; i < attrCount; i++) {
			switch (a.getIndex(i)) {
			case R.styleable.CoustomView_text:
				Log.v("x", a.getString(i));
				break;
			case R.styleable.CoustomView_color:
				Log.v("x", a.getColor(i, 0xffffff) + "");
				break;
			}
		}
		a.recycle();
	}
}

 

本文只是简单的介绍了自定义属性的流程,关于具体原理可以查看Android 深入理解Android中的自定义属性

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注