`

转:Android中自定义属性的使用------res/values文件下定义一个attrs.xml

 
阅读更多

做Android布局是件很享受的事,这得益于他良好的xml方式。使用xml可以快速有效的为软件定义界面。可是有时候我们总感觉官方定义的一些基本组件不够用,自定义组件就不可避免了。那么如何才能做到像官方提供的那些组件一样用xml来定义他的属性呢?现在我们就来讨论一下他的用法。

一、在res/values文件下定义一个attrs.xml文件,代码如下:

<?xml version="1.0" encoding="utf-8"?> 
<resources> 
    <declare-styleable name="ToolBar"> 
        <attr name="buttonNum" format="integer"/> 
        <attr name="itemBackground" format="reference|color"/> 
    </declare-styleable> 
</resources>

 

二、在布局xml中如下使用该属性:

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:toolbar="http://schemas.android.com/apk/res/cn.zzm.toolbar" 
    android:orientation="vertical" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    > 
    <cn.zzm.toolbar.ToolBar android:id="@+id/gridview_toolbar" 
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content" 
        android:layout_alignParentBottom="true" 
        android:background="@drawable/control_bar" 
        android:gravity="center" 
        toolbar:buttonNum="5" 
        toolbar:itemBackground="@drawable/control_bar_item_bg"/> 
</RelativeLayout>

 

三、在自定义组件中,可以如下获得xml中定义的值:

TypedArray a = context.obtainStyledAttributes(attrs,R.styleable.ToolBar); 
buttonNum = a.getInt(R.styleable.ToolBar_buttonNum, 5); 
itemBg = a.getResourceId(R.styleable.ToolBar_itemBackground, -1);

a.recycle();

 

就这么简单的三步,即可完成对自定义属性的使用。

*********************************************************************

好了,基本用法已经讲完了,现在来看看一些注意点和知识点吧。

首先来看看attrs.xml文件。

该文件是定义属性名和格式的地方,需要用<declare-styleable name="ToolBar"></declare-styleable>包围所有属性。其中name为该属性集的名字,主要用途是标识该属性集。那在什么地方会用到呢?主要是在第三步。看到没?在获取某属性标识时,用到"R.styleable.ToolBar_buttonNum",很显然,他在每个属性前面都加了"ToolBar_"。

在来看看各种属性都有些什么类型吧:string , integer , dimension , reference , color , enum.

前面几种的声明方式都是一致的,例如:<attr name="buttonNum" format="integer"/>。
只有enum是不同的,用法举例:

<attr name="testEnum"> 
    <enum name="fill_parent" value="-1"/> 
    <enum name="wrap_content" value="-2"/> 
</attr> 

 

如果该属性可同时传两种不同的属性,则可以用“|”分割开即可。

 

让我们再来看看布局xml中需要注意的事项。

首先得声明一下:xmlns:toolbar=http://schemas.android.com/apk/res/cn.zzm.toolbar
注意,“toolbar”可以换成其他的任何名字,后面的url地址必须最后一部分必须用上自定义组件的包名。自定义属性了,在属性名前加上“toolbar”即可。

 

最后来看看java代码中的注意事项。

在自定义组件的构造函数中,用

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

来获得对属性集的引用,然后就可以用“a”的各种方法来获取相应的属性值了。这里需要注意的是,如果使用的方法和获取值的类型不对的话,则会返回默认值。因此,如果一个属性是带两个及以上不用类型的属性,需要做多次判断,知道读取完毕后才能判断应该赋予何值。当然,在取完值的时候别忘了回收资源哦!

在xml 文件里定义控件的属性,我们已经习惯了android:attrs="" ,那么我们能不能定义自己的属性能,比如:test:attrs="" 呢?答案是肯定的.

 

进入主题。大致以下步骤:

一、 在res/values 文件下定义一个attrs.xml 文件.代码如下:

<?xml version="1.0" encoding="utf-8"?>  
<resources>  
    <declare-styleable name="MyView">  
        <attr name="textColor" format="color" />  
        <attr name="textSize" format="dimension" />  
    </declare-styleable>  
</resources>  

 二、 我们在MyView.java 代码编写如下,其中下面的构造方法是重点,我们获取定义的属性R.sytleable.MyView_textColor, 获取方法中后面通常设定默认值(float textSize = a.getDimension(R.styleable.MyView_textSize, 36 ); ), 防止我们在xml 文件中没有定义.从而使用默认值!

MyView 就是定义在<declare-styleable name="MyView "></declare-styleable> 里的 名字,获取里面属性用 名字_ 属性 连接起来就可以.TypedArray 通常最后调用 .recycle() 方法,为了保持以后使用该属性一致性!

public MyView(Context context,AttributeSet attrs)  
    {  
        super(context,attrs);  
        mPaint = new Paint();  
          
        TypedArray a = context.obtainStyledAttributes(attrs,  
                R.styleable.MyView);  
          
        int textColor = a.getColor(R.styleable.MyView_textColor,  
                0XFFFFFFFF);  
        float textSize = a.getDimension(R.styleable.MyView_textSize, 36);  
          
        mPaint.setTextSize(textSize);  
        mPaint.setColor(textColor);  
          
        a.recycle();  
    }  

 MyView.java  MyView控件全部代码如下:

package com.android.tutor;  
import android.content.Context;  
import android.content.res.TypedArray;  
import android.graphics.Canvas;  
import android.graphics.Color;  
import android.graphics.Paint;  
import android.graphics.Rect;  
import android.graphics.Paint.Style;  
import android.util.AttributeSet;  
import android.view.View;  
public class MyView extends View {  
    private Paint mPaint;  
    private Context mContext;  
    private static final String mString = "Welcome to Mr Wei's blog";  
      
    public MyView(Context context) {  
        super(context);  
        mPaint = new Paint();  
    }  
    public MyView(Context context,AttributeSet attrs)  
    {  
        super(context,attrs);  
        mPaint = new Paint();  
          
        TypedArray a = context.obtainStyledAttributes(attrs,  
                R.styleable.MyView);  
          
        int textColor = a.getColor(R.styleable.MyView_textColor,  
                0XFFFFFFFF);  
        float textSize = a.getDimension(R.styleable.MyView_textSize, 36);  
          
        mPaint.setTextSize(textSize);  
        mPaint.setColor(textColor);  
          
        a.recycle();  
    }  
    @Override  
    protected void onDraw(Canvas canvas) {  
        // TODO Auto-generated method stub  
        super.onDraw(canvas);  
        //设置填充  
        mPaint.setStyle(Style.FILL);  
          
        //画一个矩形,前俩个是矩形左上角坐标,后面俩个是右下角坐标  
        canvas.drawRect(new Rect(10, 10, 100, 100), mPaint);  
          
        mPaint.setColor(Color.BLUE);  
        //绘制文字  
        canvas.drawText(mString, 10, 110, mPaint);  
    }  
}  

 三、将我们自定义的MyView 加入布局main.xml 文件中,并且使用自定义属性,自定义属性必须加上:

    " xmlns:test ="http://schemas.android.com/apk/res/com.android.tutor"  ,test是自定义属性的前缀,           com.android.tutor 是我们包名.


main.xml 全部代码如下:

<?xml   
version="1.0" encoding="utf-8"?>  
<LinearLayout   
xmlns:android="http://schemas.android.com/apk/res/android"  
                
xmlns:test="http://schemas.android.com/apk/res/com.android.tutor"  
    android:orientation="vertical"  
    android:layout_width="fill_parent"  
    android:layout_height="fill_parent"  
    >  
<TextView    
    android:layout_width="fill_parent"   
    android:layout_height="wrap_content"   
    android:text="@string/hello"  
    />  
<com.android.tutor.MyView  
    android:layout_width="fill_parent"   
    android:layout_height="fill_parent"   
    test:textSize="20px"  
    test:textColor="#fff"  
/>  
</LinearLayout>  

 四、运行之效果如下图:

 

 参考文章二:

Android 自定义View 己经不是什么新鲜话题,Android Api提供了一大堆基础组件给我们,需要什么特定功能还需要我们继承它们然后定制更加丰富的功能。前面有篇文章也说过为自定义VIEW添加属性,但只是一笔带过,这里就拿这点来说说吧。

第一种添加属性的方法,之前我也是经常使用这种写法,代码如下:

package com.terry.attrs;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

public class EditTextExt1 extends LinearLayout {

    private String Text = "";

    public EditTextExt1(Context context) {
        this(context, null);
        // TODO Auto-generated constructor stub
    }

    public EditTextExt1(Context context, AttributeSet attrs) {
        super(context, attrs);
        // TODO Auto-generated constructor stub
        int resouceId = -1;

        TextView tv = new TextView(context); 
        EditText et = new EditText(context);

        resouceId = attrs.getAttributeResourceValue(null, "Text", 0);
        if (resouceId > 0) {
            Text = context.getResources().getText(resouceId).toString();
        } else {
            Text = "";
        }
        tv.setText(Text);

        addView(tv);
        addView(et, new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
                LayoutParams.WRAP_CONTENT));
        this.setGravity(LinearLayout.VERTICAL);

    }

}

 


这种写法,简单明了,不需要额外XML的配置,就可以在我们的VIEW文件下使用。

以上代码通过构造函数中引入的AttributeSet 去查找XML布局的属性名称,然后找到它对应引用的资源ID去找值。使用也时分方便。所以一直以来我也是很喜欢这种写法。

如上,自定好VIEW文件就可以在XML布局下如此使用:

<com.terry.attrs.EditTextExt1 
        android:id="@+id/ss3"
        android:layout_width="wrap_content"   
        android:layout_height="wrap_content"
        Text="@string/app_name" >
</com.terry.attrs.EditTextExt1>

 好了,这是第一种为VIEW注册属性的写法,比较简单就不多介绍。

下面是第二为VIEW注册属性的写法,这里也要重点说说第二种注册 属性的写法和使用要点,先看一下JAVA代码要如何编写:

package com.terry.attrs;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

public class EditTextExt extends LinearLayout {

    public EditTextExt(Context context) {
        this(context, null);
        // TODO Auto-generated constructor stub
    }

    public EditTextExt(Context context, AttributeSet attrs) {
        super(context, attrs);
        // TODO Auto-generated constructor stub
        int resouceId = -1;
        TypedArray typeArray = context.obtainStyledAttributes(attrs,
                R.styleable.EditTextExt);

        TextView tv = new TextView(context);
        EditText et = new EditText(context);
        
        int N = typeArray.getIndexCount();
        for (int i = 0; i < N; i++) {
            int attr = typeArray.getIndex(i);
            switch (attr) {
            case R.styleable.EditTextExt_Oriental:
                resouceId = typeArray.getInt(R.styleable.EditTextExt_Oriental,
                        0);
                this.setOrientation(resouceId == 1 ? LinearLayout.HORIZONTAL
                        : LinearLayout.VERTICAL);
                break;
            case R.styleable.EditTextExt_Text:
                resouceId = typeArray.getResourceId(
                        R.styleable.EditTextExt_Text, 0);
                tv.setText(resouceId > 0 ? typeArray.getResources().getText(
                        resouceId) : typeArray
                        .getString(R.styleable.EditTextExt_Text));
                break;
            }
        }
        addView(tv);
        addView(et);
        typeArray.recycle();

    }
}

 如上代码,跟前面代码一样。还是用的一个EDITTEXT和TEXTVIEW做基础组件。下面我们一步步分析上面的代码:
R.styleable.EditTextExt 代码的是一个attrs指向的一个declare-styleable 的标签,如下代码:

<?xml version="1.0" encoding="UTF-8"?>
<resources>
    <declare-styleable name="EditTextExt">
        <attr name="Text" format="reference|string"></attr>
        <attr name="Oriental">
            <enum name="Horizontal" value="1"></enum>
            <enum name="Vertical" value="0"></enum>
        </attr>
    </declare-styleable>
</resources>

 这个文件位于,values下的attrs.xml目录下面,我比较喜欢一个自定义View 对应一个declare-styleable标签。

Tip:一个自定义View 第一部分的代码,

TypedArray typeArray = context.obtainStyledAttributes(attrs, R.styleable.EditTextExt);

 指定为一个declare-styleable,而在declare-styleable 下的attr (即各属性)Android 的ADT 将会自动生成为declare-styleable的name 名字加上“_”加上对应attr(即属性名称)的名称,如上(EditTextExt_Text)我们要得到Text 就需要R.styleable.EditTextExt_Text,这一点的话可以看看R.java生成文件:

public static final class styleable {
    /**
     * Attributes that can be used with a EditTextExt. Includes the following
     * attributes: Attribute Description {@link #EditTextExt_Oriental
     * com.terry.attrs:Oriental} {@link #EditTextExt_Text com.terry.attrs:Text}
     * 
     * @see #EditTextExt_Oriental
     * @see #EditTextExt_Text
     */
    public static final int[] EditTextExt = { 0x7f010000, 0x7f010001 };

    /**
     * This symbol is the offset where the
     * {@link com.terry.attrs.R.attr#Oriental} attribute's value can be found in
     * the {@link #EditTextExt} array. Must be one of the following constant
     * values. Constant Value Description Horizontal 1 Vertical 0
     * 
     * @attr name android:Oriental
     */
    public static final int EditTextExt_Oriental = 1;

    /**
     * This symbol is the offset where the {@link com.terry.attrs.R.attr#Text}
     * attribute's value can be found in the {@link #EditTextExt} array. May be
     * a reference to another resource, in the form "@[+][package:]type:name" or
     * to a theme attribute in the form "?[package:][type:]name". May be a
     * string value, using '//;' to escape characters such as '//n' or '//uxxxx'
     * for a unicode character. 
     * 
     * @attr name android:Text
     */
    public static final int EditTextExt_Text = 0;
};

 好了,上述的代码写完,我们要在XML布局如何使用呢?这个会跟Android 提供的基础组件的使用方法是一致的。首先,我们要为其提供一个引用包名如下:

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

 上面提供的是android 基础组件的包名,和我们自己组件的包名。

写好了包名。就可以像使用andriod 基础组件一样使用了,如下全部XML布局源码:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:terry="http://schemas.android.com/apk/res/com.terry.attrs"
    android:orientation="vertical" android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <TextView android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:text="@string/hello" />

    <com.terry.attrs.EditTextExt android:id="@+id/ss"
        android:layout_width="fill_parent" android:layout_height="wrap_content"
        terry:Text="fdsafda" terry:Oriental="Vertical"></com.terry.attrs.EditTextExt>

    <com.terry.attrs.EditTextExt1 android:id="@+id/ss3"
        android:layout_width="wrap_content" android:layout_height="wrap_content"
        Text="@string/app_name"  ></com.terry.attrs.EditTextExt1>
</LinearLayout>

 
 运行效果如下:

这是这两种为Android 注册 属性的使用方法,那么两者有什么区别呢?

在这里我认为起码有五点,大家可以找找看还有什么区别:

第二种可以编译时报错,如果编程人员随便输入什么第一种是不会报错的,第二种可以支持代码检测功能。
第二种写法,跟Android 属性标准写法是一致的,而且可以统一书法规则。
第二种写法,可以支持数据格式的验证,比如我们在attrs上注明只支持integer 那么就不可以使用字符串,这是第一种达不到的。
第二种写法,可以为VIEW提供选择操作,比如如上我们使用的ENUM让VIEW对应的属性支持ENUM列表,或者为其提供BOOL等只有双项选择的操作。
第一种写法,所有的属性必须是引用自资源(不大确定,如果朋友有什么好的DEMO麻烦共享),第二种写法,可以即支持引用资源又可以直接输入做操作,为编程带来更多的方便性。
种种都说明,第二种写法更具规范性,功能更性,代码编写 也更优雅,但个人有个人的使用习惯,我两种都喜欢用,具体看需求吧。

分享到:
评论

相关推荐

    Android代码-VerificationCodeView

    Eclipse:下载项目,将library里面的VerificationCodeView.java跟res/values/attrs.xml文件拷贝进项目。 二、用法 在布局中集成,注意需要在布局的根节点添加命名xmlns:zhangym=...

    attrs.xml文件

    解决error: No resource identifier found for attribute 'cardCornerRadius' in package 'com.example.test' android\sdk\extras\android\support\v7\cardview\res\values\attrs.xml 把这个拷贝到工程目录下就有了

    Android UI开发专题

    本次主要涉及以下四个包的相关内容: android.content.res 资源类  android.graphics 底层图形类  android.view 显示类  android.widget 控件类  一、android.content.res.Resources  对于Android平台的资源...

    Android代码-ProgressWheel

    Add the following to your attrs.xml file &#40;in res/values&#41;: 2. Add the following code to the root view of your layout: `xmlns:ProgressWheel=...

    Android--UI-新手必备源码master.zip

    包括Android布局,弹窗,配色,单击事件,UI,精美炫酷的activity切换动画和空间动画,是新手必备的源码,内含相关的Dome 25件。 - - 文件夹 PATH 列表 卷序列号为 4E8D-6931 C:. │ .txt │ Android-UI-新手必备...

    详解Android自定义控件属性

    在文件res/values/下新建attrs.xml属性文件,中定义我们所需要的属性。 &lt;?xml version=1.0 encoding=utf-8?&gt; &lt;resources&gt;&lt;!-- resource是跟标签,可以在里面定义若干个declare-styleable --&gt; ...

    Android实现自定义组合控件

    将attrs.xml文件直接复制到res/values目录下,布局文件放在res/layout目录下

    Android自定义控件之自定义属性(二)

    前言: 上篇介绍了自定义控件的基本要求以及绘制的基本原理,本篇文章主要介绍如何给自定义控件自定义一些...1.)在res/values文件下添加一个attrs.xml文件,如果项目比较大的话,会导致attrs.xml代码相当庞大,这时可

    drawable跟随TextView居中.zip

    你只需要这添加这两个文件就可以使用了! deadline/DrawableTextView.java res/values/attrs.xml ###代码中这样设置即可 drawable = ContextCompat.getDrawable(getContext(), R.mipmap.xxx); setDrawable...

    tigase-mobilemessenger

    │ │ │ AndroidManifest.xml │ │ │ │ │ ├─java │ │ │ └─org │ │ │ └─tigase │ │ │ └─messenger │ │ │ ├─jaxmpp │ │ │ │ └─android │ │ │ │ ├─caps │ │ │ │ │ ...

    Android重写View并自定义属性实例分析

    本文实例分析了Android重写View并自定义属性的...第一步:在res\values的目录下新建一个文件attrs.xml 声明一些自定义属性 &lt;?xml version=1.0 encoding=utf-8?&gt; &lt;attr name=customTextColor format=c

    Android雷达图(蜘蛛网图)源码

    需要在res/values/attrs.xml中添加以下 &lt;declare-styleable name="MyNetPic"&gt; &lt;attr name="lineColor" format="color"/&gt;&lt;!-- 线的颜色 --&gt; &lt;attr name="cotentColor" format="color"/&gt;&lt;!-- 图形的颜色 --&gt; ...

    Android App中自定义View视图的实例教程

    一、基础 很多的Android入门程序猿来说对于Android自定义View,可能都是...1、自定义View的属性,首先在res/values/ 下建立一个attrs.xml , 在里面定义我们的属性和声明我们的整个样式。   &lt;?xml version=1.0

    Android自定义View编写随机验证码

    很多的Android入门程序猿来说对于Android自定义View,可能都是比较恐惧的,...1、自定义View的属性,首先在res/values/ 下建立一个attrs.xml , 在里面定义我们的属性和声明我们的整个样式。 &lt;?xml version=1.0 e

    Android自定义View多种效果解析

    1.首先在我们的res/values/目录下建立一个attrs.xml文件,然后在里面声明我们我们需要的自定义属性 我们定义了矩形的颜色,矩形的高度,矩形的宽度3个属性,format是指该属性的取值类型: 一共有:string,color,...

    Android自定义View圆形百分比控件(一)

    1、在res/values文件夹下新建attrs.xml文件,编写自定义属性: &lt;?xml version=1.0 encoding=utf-8?&gt; &lt;attr name=circleBg format=color/&gt; &lt;attr name=arcColor format=color/&gt; &lt;attr name=

    Android自定义View实现颜色选取器

    Android 自定义View 颜色选取器,可以...复制 \library\src…\ColorPickerView.java 和 \library\src\main\res\values\attrs.xml 文件到你的项目中,就可以在使用啦。 示例: 在 xml 中使用: &lt;com.duan.colorpic

    Android代码-CoolImageView

    CoolImageView A imageView is similar to QQ that imageView background picture can move up and down,But ...step1: Add the following to your attrs.xml file &#40;in res/values&#41;: step2:Add the follo

    Android自定义View仿微博运动积分动画效果

    自定义View一直是自己的短板,趁着公司项目不紧张的时候,多加强这方面的练习。...在res/values/ 下建立一个attrs.xml , 在里面定义我们的属性以及声明我们的整个样式。 &lt;?xml version=1.0 enco

    Android自定义View圆形进度条控件(三)

    继续练习自定义View,这次带来的圆形进度条控件与之前的圆形...1、在res/values文件夹下新建attrs.xml文件,编写自定义属性: &lt;?xml version=1.0 encoding=utf-8?&gt; &lt;!-- 弧线宽度 --&gt; &lt;!--

Global site tag (gtag.js) - Google Analytics