8

安卓开发小技巧,教你们如何用文本 XML 动态生成界面。

 2 years ago
source link: https://www.v2ex.com/t/790800
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

V2EX  ›  Android

安卓开发小技巧,教你们如何用文本 XML 动态生成界面。

  3dwelcome · 1 小时 52 分钟前 · 234 次点击

第一步,运行时动态下载 Layout XML 文件,用 binxml 之类的工具函数,转换成 Byte[]类型的二进制 XML (模仿 AndroidStudio 的资源编译流程)

第二步,把每个按钮的资源 ID 包名赋值一下,因为动态载入 Layout 的 JAVA 函数,会自动去 resources.arsc 资源列表查找对应的 ID,而按钮是动态生成的,根本就没有 ID,需要随便分配一个,只要当前 View 内不重复即可。

第三步,用 LayoutInflater.inflate 和老外写的 XmlBlock 内部资源解析函数,正式加载二进制 XML 界面,转换成 View 组件。( https://github.com/liudongmiao/preference-fragment-compat/blob/master/src/me/piebridge/android/preference/PreferenceFragment.java#L235 )

第四步,用 findViewById 查找按钮的 view, 用 setOnClickListener 设置响应事件,setContentView 显示出来,搞定收工。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK