自定义属性剖析

简介: 上一节已经说了自定义属性的用法,实现步骤有如下几步:自定义一个CustomView(extends View )类编写values/attrs.
上一节已经说了自定义属性的用法,实现步骤有如下几步:
  1. 自定义一个CustomView(extends View )类
  2. 编写values/attrs.xml,在其中编写declare-styleable和attr等标签元素
  3. 在布局文件中CustomView使用自定义的属性(注意添加自己的namespace)
  4. 在CustomView的构造方法中通过TypedArray获取自定义属性

知道了这些,我们完全可以写自己的view了,但为什么要这样呢?它是如何运行的呢?正所谓知其然,更要知其所以然,看了鸿洋大神的文章,真是有种醍醐灌顶的感觉啊
好了,不拍马屁了,切入正题

首先,写一个自定义属性文件

<resources>

    <!-- declare-styleable的 name是可以随便取名字的 -->
    <declare-styleable name="CustomAttrView">
        <attr name="text" format="string" />
    </declare-styleable>

</resources>

编写自定义view

public class CustomAttrView extends View {

    String TAG = "tag";
    Paint paint;
    String text;

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

    public CustomAttrView(Context context, AttributeSet attrs) {
        super(context, attrs);
        paint = new Paint();
        TypedArray typedArray = context.obtainStyledAttributes(attrs,
                R.styleable.CustomAttrView);

        text = typedArray.getString(R.styleable.CustomAttrView_text);
        Log.i(TAG, "--text = " + text);
        typedArray.recycle();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        paint.setTextSize(80);
        canvas.drawText(text, 80f, 80f, paint);
    }
}

在activity_main.xml文件中引用
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <com.example.activity.view.CustomAttrView
        android:layout_width="200dp"
        android:layout_height="100dp"
        custom:text="520" />

</RelativeLayout>

运行后输出的log日志为:



继续看代码,构造函数里有一个AttributeSet (参数集),具体的用途是什么?
修改下CustomAttrView

public CustomAttrView(Context context, AttributeSet attrs) {
        super(context, attrs);
        paint = new Paint();
        TypedArray typedArray = context.obtainStyledAttributes(attrs,
                R.styleable.CustomAttrView);

        text = typedArray.getString(R.styleable.CustomAttrView_text);
        Log.i(TAG, "--text = " + text);

        typedArray.recycle();

        int count = attrs.getAttributeCount();
        for (int i = 0; i < count; i++) {
            String attrName = attrs.getAttributeName(i);
            String attrVal = attrs.getAttributeValue(i);
            Log.i(TAG, "--attrName = " + attrName + " , attrVal = " + attrVal);
        }
    }
看下log输出

可以看出,AttributeSet保存的是该View声明的所有的属性,通过AttributeSet可以获得布局文件中定义的所有属性的key和value(还有一些方法,根据提示可以用下)
对比两次log,好像TypedArray并没有什么用,想要获得我自定义的text属性直接用AttributeSet也可以,好,修改下activity_main.xml

   <com.example.activity.view.CustomAttrView
        android:layout_width="@dimen/dp200"
        android:layout_height="@dimen/dp100"
        custom:text="@string/hello_world" />
再次运行,看下log

通过AttributeSet获取的值,如果是引用都变成了@+数字的字符串。而使用TypedArray获取的值没有变化。TypedArray的作用现在明白了——TypedArray其实是用来简化我们的工作的,比如上例,如果布局中的属性的值是引用类型(比如:@dimen/dp100),如果使用AttributeSet去获得最终的像素值,那么需要先拿到id,然后再去解析id。而TypedArray正是帮我们简化了这个过程

捎带一下通过AttributeSet获取最终的像素值的过程:

int widthDimensionId =  attrs.getAttributeResourceValue(0, -1);
        Log.e(TAG, "layout_width= "+getResources().getDimension(widthDimensionId));

我的自定义属性文件只写了一个custom:text,很多情况下自定义属性的含义在android系统中已经有了明确的定义,比如我这个,那么直接使用android:text是否可以?

修改下attrs.xml

 <declare-styleable name="CustomAttrView">
        <attr name="android:text" />
    </declare-styleable>

因为我们使用的是已经定义好的属性,所以不需要去添加format属性(声明和使用的区别就是有没有format)。 
然后在类中这么获取:typedArray.getString(R.styleable.CustomAttrView_android_text);

布局文件中直接android:text="@string/hello_world"即可。

系统中定义的属性,其实和我们自定义属性的方式类似,你可以在sdk/platforms/android-xx/data/res/values该目录下看到系统中定义的属性。然后你可以在系统提供的View(eg:TextView)的构造方法中发现TypedArray获取属性的代码(自己去看一下)。

既然declare-styleable这个标签的name都能随便写,那么考虑问题:

styleable 的含义是什么?可以不写嘛?我自定义属性,我声明属性就好了,为什么一定要写个styleable呢?

其实的确是可以不写的,怎么做呢?


首先删除declare-styleable的标签

atrrs.xml变为
<?xml version="1.0" encoding="utf-8"?>
<resources> 
<attr name="text" format="string" />
</resources>

 
 
CustomAttrView.java如下

public class CustomAttrView extends View {

    String TAG = "tag";
    Paint paint;
    String text;
    private static final int[] mAttr = { R.attr.text };
    private static final int ATTR_ANDROID_TEXT = 0;

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

    public CustomAttrView(Context context, AttributeSet attrs) {
        super(context, attrs);
        paint = new Paint();
        TypedArray typedArray = context.obtainStyledAttributes(attrs, mAttr);

        text = typedArray.getString(ATTR_ANDROID_TEXT);
        Log.i(TAG, "--text = " + text);

        typedArray.recycle();

    }

}
对比下两个构造函数,可以看到我们声明了一个int数组,数组中的元素就是我们想要获取的attr的id。并且我们根据元素的在数组中的位置,定义了一些整形的常量代表其下标,然后通过TypedArray进行获取。
还有如下区别:
R.styleable.CustomAttrView ——> mAttr
R.styleable.CustomAttrView_text——> ATTR_ANDROID_TEXT(0)

其实android在其内部也会这么做,按照传统的写法,它会在R.java生成如下代码:
 
  
public static final class attr {
      
        public static final int text = 0x7f010000;
    }
 
  
public static final class styleable {
 public static final int[] CustomAttrView = {
            0x7f010000
        };
    public static final int CustomAttrView_text = 0;
    };
}
styleale的的作用就是使系统可以完成很多常量(int[]数组,下标常量等)的编写,简化我们的开发工作。那么大家肯定还知道declare-styleable的name属性, 一般情况下写的都是我们自定义View的类名。主要为了直观的表达,该declare-styleable的属性,都是改View所用的。
套用下鸿洋大神的总结:
  • attrs.xml里面的declare-styleable以及item,android会根据其在R.java中生成一些常量方便我们使用(aapt干的),本质上,我们可以不声明declare-styleable仅仅声明所需的属性即可。
  • 我们在View的构造方法中,可以通过AttributeSet去获得自定义属性的值,但是比较麻烦,而TypedArray可以很方便的去获取。
  • 我们在自定义View的时候,可以使用系统已经定义的属性。


源代码


参考:

http://blog.csdn.net/lmj623565791/article/details/45022631

相关文章
|
16天前
|
人工智能 JSON API
全网刷屏的 Jev 模型正式开放!一手实战测评 + 保姆级教程
全网爆火的 Jev 模型是什么?有什么用?怎么使用?怎么接入 AI 编程工具?效果真的好么?傻子可懂的 Jev 保姆级实战教程 + 项目实战测评来啦
8213 18
|
14天前
|
人工智能 并行计算 PyTorch
秋叶 ComfyUI 2026 整合包 v3.2 完整部署教程:Python 3.13 + Torch 2.13 全栈升级
秋叶aaaki ComfyUI 2026年8月整合包v3.2正式发布!全面升级Python 3.13.11、PyTorch 2.13.0+cu130及ComfyUI v0.30.2,原生支持MiniMax H3、Wan 2.2、Qwen-Image-2.1等2026主流音视频/图像模型,解压即用,无需环境配置。
2469 13
|
14天前
|
人工智能 测试技术 API
最近全网爆火的 Jev 到底是什么?适合干什么、怎么用,一篇讲透!
Jev是TypeSafe AI推出的“系统一模型”,不生成文本,专做毫秒级结构化决策:Choice(多选)、Score(打分)、Noul(是非概率)。响应快193倍、成本低444倍,适合工单路由、内容审核、测试定级等高频判断场景。
1862 4
最近全网爆火的 Jev 到底是什么?适合干什么、怎么用,一篇讲透!
|
13天前
|
人工智能 编解码 并行计算
MiniMax-H3 一键整合包技术文档:8G 显存运行 AI 漫剧制作 —— 角色替换 / 动作迁移 / 文图生视频部署与调参指南
MiniMax H3 是 MiniMax 开源的全模态视频生成模型,支持文/图/音/视多条件输入,输出最高2K、15秒带双声道音频视频。本文档详述其Int8量化版在8GB显存下的本地一键部署、三段式工作流(EDIT/REPLACE/CONTINUE)、参数调优及常见问题排查。(239字)
|
8天前
|
人工智能 Linux 开发者
【2026国内使用】Codex安装过程一篇讲透(Win/Mac/Linux全支持)
Codex是OpenAI推出的AI编程智能体,可读取本地项目、理解需求并自动修改代码。支持桌面GUI、命令行(CLI)及VS Code/Cursor插件三种形态,覆盖可视化操作、终端高效开发与编辑器无缝集成场景,助开发者用自然语言驱动编码全流程。(239字)
【2026国内使用】Codex安装过程一篇讲透(Win/Mac/Linux全支持)
|
8天前
|
人工智能 JSON 编解码
【2026最新版】ComfyUI本地部署教程,新手也能看懂!
ComfyUI是本地运行的AI绘画工具,采用节点式工作流设计:通过拖拽连接“加载模型”“提示词编码”“采样”“解码”等模块,实现高度可控的文生图。新手推荐使用秋叶整合包,一键启动、内置模型管理与插件安装器,轻松上手。(239字)
|
22天前
|
缓存 IDE Java
【保姆级】Android Studio下载、安装和汉化教程(2026最新)
Android Studio 是 Google 官方推出的免费 Android 应用开发集成环境,基于 IntelliJ IDEA,内置模拟器、调试器、性能分析及 Compose 界面工具,功能全面,文档丰富,是安卓开发首选工具。(239字)
2420 1

热门文章

最新文章