热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

说说Android两种为自定义组件添加属性的使用方法和区别

Android自定义View己经不是什么新鲜话题,AndroidApi提供了一大堆基础组件给我们,需要什么特定功能还需要我们继承它们然后定制更加丰富的功能。前面有篇文章也说过为自定义VIEW添加

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:


           
           
           
           

           
           
           
AttributeDescription
{@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 = {
            
0x7f0100000x7f010001
        };
        
/**
          

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.









ConstantValueDescription
Horizontal1
Vertical0

          @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麻烦共享),第二种写法,可以即支持引用资源又可以直接输入做操作,为编程带来更多的方便性。

种种都说明,第二种写法更具规范性,功能更性,代码编写 也更优雅,但个人有个人的使用习惯,我两种都喜欢用,具体看需求吧。呵呵。。。

源码下载:属性DEMO


推荐阅读
  • XML介绍与使用的概述及标签规则
    本文介绍了XML的基本概念和用途,包括XML的可扩展性和标签的自定义特性。同时还详细解释了XML标签的规则,包括标签的尖括号和合法标识符的组成,标签必须成对出现的原则以及特殊标签的使用方法。通过本文的阅读,读者可以对XML的基本知识有一个全面的了解。 ... [详细]
  • 在Xamarin XAML语言中如何在页面级别构建ControlTemplate控件模板
    本文介绍了在Xamarin XAML语言中如何在页面级别构建ControlTemplate控件模板的方法和步骤,包括将ResourceDictionary添加到页面中以及在ResourceDictionary中实现模板的构建。通过本文的阅读,读者可以了解到在Xamarin XAML语言中构建控件模板的具体操作步骤和语法形式。 ... [详细]
  • 本文分享了一个关于在C#中使用异步代码的问题,作者在控制台中运行时代码正常工作,但在Windows窗体中却无法正常工作。作者尝试搜索局域网上的主机,但在窗体中计数器没有减少。文章提供了相关的代码和解决思路。 ... [详细]
  • 开发笔记:加密&json&StringIO模块&BytesIO模块
    篇首语:本文由编程笔记#小编为大家整理,主要介绍了加密&json&StringIO模块&BytesIO模块相关的知识,希望对你有一定的参考价值。一、加密加密 ... [详细]
  • 本文讨论了一个关于cuowu类的问题,作者在使用cuowu类时遇到了错误提示和使用AdjustmentListener的问题。文章提供了16个解决方案,并给出了两个可能导致错误的原因。 ... [详细]
  • 后台获取视图对应的字符串
    1.帮助类后台获取视图对应的字符串publicclassViewHelper{将View输出为字符串(注:不会执行对应的ac ... [详细]
  • CF:3D City Model(小思维)问题解析和代码实现
    本文通过解析CF:3D City Model问题,介绍了问题的背景和要求,并给出了相应的代码实现。该问题涉及到在一个矩形的网格上建造城市的情景,每个网格单元可以作为建筑的基础,建筑由多个立方体叠加而成。文章详细讲解了问题的解决思路,并给出了相应的代码实现供读者参考。 ... [详细]
  • 本文介绍了南邮ctf-web的writeup,包括签到题和md5 collision。在CTF比赛和渗透测试中,可以通过查看源代码、代码注释、页面隐藏元素、超链接和HTTP响应头部来寻找flag或提示信息。利用PHP弱类型,可以发现md5('QNKCDZO')='0e830400451993494058024219903391'和md5('240610708')='0e462097431906509019562988736854'。 ... [详细]
  • 本文介绍了一款名为TimeSelector的Android日期时间选择器,采用了Material Design风格,可以在Android Studio中通过gradle添加依赖来使用,也可以在Eclipse中下载源码使用。文章详细介绍了TimeSelector的构造方法和参数说明,以及如何使用回调函数来处理选取时间后的操作。同时还提供了示例代码和可选的起始时间和结束时间设置。 ... [详细]
  • 本文介绍了一种在PHP中对二维数组根据某个字段进行排序的方法,以年龄字段为例,按照倒序的方式进行排序,并给出了具体的代码实现。 ... [详细]
  • Activiti7流程定义开发笔记
    本文介绍了Activiti7流程定义的开发笔记,包括流程定义的概念、使用activiti-explorer和activiti-eclipse-designer进行建模的方式,以及生成流程图的方法。还介绍了流程定义部署的概念和步骤,包括将bpmn和png文件添加部署到activiti数据库中的方法,以及使用ZIP包进行部署的方式。同时还提到了activiti.cfg.xml文件的作用。 ... [详细]
  • 带添加按钮的GridView,item的删除事件
    先上图片效果;gridView无数据时显示添加按钮,有数据时,第一格显示添加按钮,后面显示数据:布局文件:addr_manage.xml<?xmlve ... [详细]
  • Sleuth+zipkin链路追踪SpringCloud微服务的解决方案
    在庞大的微服务群中,随着业务扩展,微服务个数增多,系统调用链路复杂化。Sleuth+zipkin是解决SpringCloud微服务定位和追踪的方案。通过TraceId将不同服务调用的日志串联起来,实现请求链路跟踪。通过Feign调用和Request传递TraceId,将整个调用链路的服务日志归组合并,提供定位和追踪的功能。 ... [详细]
  • Java图形化计算器设计与实现
    本文介绍了使用Java编程语言设计和实现图形化计算器的方法。通过使用swing包和awt包中的组件,作者创建了一个具有按钮监听器和自定义界面尺寸和布局的计算器。文章还分享了在图形化界面设计中的一些心得体会。 ... [详细]
  • 今天就跟大家聊聊有关怎么在Android应用中实现一个换肤功能,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根 ... [详细]
author-avatar
Shimmoon
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有