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 文件中搜搜看
notion image
我们再通过自定义属性的名称 MaterialEditText 在 R 文件中搜搜看
notion image
可以看出 MaterialEditText 是一个数组,数组中的两个值可以查找到:
notion image
notion image
这样我们就能大概明白代码的逻辑了
这一行,
attrs 中的结构大概是
通过 R.styleable.MaterialEditText 能过解析出其中保存了 customAttributeuseFloatingLabel 两个 attr 的索引值
obtainStyledAttributes 方法是为了从 attrs(包含了所有的 attr 和对应的索引值)中筛选出包含 MaterialEditText 数组中的 attr 的值(返回 TypedArray 对象),也就是customAttribute=0x7f030079:1useFloatingLabel=0x7f0301c1:false
然后就可以通过 TypedArray 中通过属性的索引取出对应的值,这里就是通过R.styleable.MaterialEditText_useFloatingLabel=0x7f0301c1 取到值为 false 的
所以上面取值的方法也可以这么写
View 绘制流程-源码解析自定义布局
Loading...
shuouyang
shuouyang
android开发 ReactNative开发 小程序开发
最新发布
AOSP 环境搭建
2025-3-29
View 绘制流程-源码解析
2025-3-12
HTTP
2025-3-4
JVM 虚拟机
2025-2-28
蓝牙-BLE-基础
2025-2-28
从 OkHttp 的原理来看 HTTP
2025-2-19
公告
🎉热点信息🎉
--- 1 ---
Jet Brains 推出新的跨平台支持 Kotlin MultiPlatform
--- 2 ---
新的小巧便捷的依赖注入框架 Koin
--- 3 ---
新一代 API 查询语言 GraphQL