type
status
date
slug
summary
tags
category
password
icon
Styleable 过程是怎么样的?
案例代码
自定义属性
布局文件
获取自定义属性的代码
View 构造方法中传入的 attrs 会保存XML中使用这个 View 时,给他设置的属性,而
context.obtainStyledAttributes(attrs, R.styleable.自定义)
,会从 attrs 中筛选出只在 R.styleable.自定义 中定义的属性,并返回一个 TypedArray,然后就可以通过 TypedArray 去获取 R.styleable.自定义 中的属性对应的值。上面这行代码会输出
我们把上面的 id 从十进制转为十六进制是 0x7f080098,然后去 R 文件中搜搜看

我们再通过自定义属性的名称
MaterialEditText
在 R 文件中搜搜看
可以看出 MaterialEditText 是一个数组,数组中的两个值可以查找到:


这样我们就能大概明白代码的逻辑了
这一行,
attrs 中的结构大概是
通过
R.styleable.MaterialEditText
能过解析出其中保存了 customAttribute
和 useFloatingLabel
两个 attr 的索引值obtainStyledAttributes
方法是为了从 attrs(包含了所有的 attr 和对应的索引值)中筛选出包含 MaterialEditText 数组中的 attr 的值(返回 TypedArray 对象),也就是customAttribute=0x7f030079:1
和 useFloatingLabel=0x7f0301c1:false
然后就可以通过
TypedArray
中通过属性的索引取出对应的值,这里就是通过R.styleable.MaterialEditText_useFloatingLabel=0x7f0301c1
取到值为 false 的所以上面取值的方法也可以这么写
- 作者:shuouyang
- 链接:https://notion-tree.vercel.app/article/0af7c8ad-d811-42b4-bb4c-f004a43dcc2c
- 声明:本文采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处。