Android自定义属性

一、前言:

        我们在开发应用时,会经常去自定义一些UI控件,而这些UI控件可能是一个小功能,或是一个复合型的大功能集合,如果是大功能集合,可能会根据不同的需求,提供给用户一些可选择属性,并完成不同的功能;这里所说的“可选择属性”,其实就是在layout.xml中,在自定义控件里,可以提供调用者来设置一些属性。

二、自定义属性:

        2.1 我们来看个例子:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:uiscroll="http://schemas.android.com/apk/res/com.chris.apps.uiscroll"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >
	
    <com.chris.apps.uiscroll.UIScrollLayout
        android:id="@+id/scrollLayout"
        uiscroll:view_type="navigator"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

		......
		
    </com.chris.apps.uiscroll.UIScrollLayout>
	
</RelativeLayout>

        自定义一个UIScrollLayout控件,具体做啥暂时不说了,这个控件会在之后放到博文中。其实,有行属性:

        uiscroll:view_type="navigator"

        定义了该view类型是"navigator",当然,还支持"slidemenu"。在代码中,看看如何加载该属性值:

	private final static String ATTR_NAVIGATOR	= "navigator";
	private final static String ATTR_SLIDEMENU	= "slidemenu";
	public final static int VIEW_NAVIGATOR 	= 0;
	public final static int VIEW_MAIN_SLIDEMENU	= 1;
	private int mViewType = VIEW_NAVIGATOR;
	
	public UIScrollLayout(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		
		TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.UIScroll);
		String type = a.getString(R.styleable.UIScroll_view_type);
		a.recycle();
		
		Log.d(TAG, "type = " + type);
		if(type.equals(ATTR_NAVIGATOR)){
			mViewType = VIEW_NAVIGATOR;
		}else if(type.equals(ATTR_SLIDEMENU)){
			mViewType = VIEW_MAIN_SLIDEMENU;
		}
	}

        TypedArray,在Java Framewoke中,随处可见,通过读取xml字段中的值,来完成一些初始化的事。

        2.2 定义:

        第一步:在res/values目录下,新建一个attrs.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="UIScroll">
        <attr name="view_type" format="string" />
    </declare-styleable>
</resources>

        这个没啥说的,定义一个styleable名字,然后,添加一个属性为string类型,其它类型有:

        string , integer , dimension , reference , color , enum。

        第二步:在要用到的layout.xml中的开关,添加:

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

        xmlns:<名称>,名称可随便定义,然后,后面写上具体的schemas(包名);

        第三步:在需要用的地方使用即可:

    uiscroll:view_type="navigator"

        <名称>:<属性>=<值>

        OK!完成,希望大家在自定义控件中,多用这些,以帮助你或别人,在重复使用你的控件之时,能够多一点选择与应便。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值