Android 学习记录 - 动态加载布局

Android 学习记录 - 动态加载布局,第1张

概述ViewGroup可以通过addView加载布局ViewGroup有LinearLayout、RelativeLayout等通过LinearLayout.LayoutParamslp=newLinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT),可以设置LinearLayout相关属性值通过继承一种ViewGroup自定义其组

VIEwGroup 可以通过 addVIEw 加载子布局
VIEwGroup 有 linearLayout、relativeLayout 等
通过linearLayout.LayoutParams lp = new linearLayout.LayoutParams(VIEwGroup.LayoutParams.WRAP_CONTENT),可以设置 linearLayout 相关属性值
通过继承一种 VIEwGroup 自定义其组合控件
构造函数使用 LayoutInflater.from(context).inflate() 加载布局,或者使用 context: LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) 或 activity:LayoutInflater inflater = activity.getLayoutInflater() 获得 inflater 实例,再使用 inflate() 方法

API 文档:

/** * Instantiates a layout XML file into its corresponding {@link androID.vIEw.VIEw} * objects. It is never used directly. Instead, use * {@link androID.app.Activity#getLayoutInflater()} or * {@link Context#getSystemService} to retrIEve a standard LayoutInflater instance * that is already hooked up to the current context and correctly configured * for the device you are running on.  For example: * * <pre>LayoutInflater inflater = (LayoutInflater)context.getSystemService *      (Context.LAYOUT_INFLATER_SERVICE);</pre> *  * <p> * To create a new LayoutInflater with an additional {@link Factory} for your * own vIEws, you can use {@link #cloneInContext} to clone an existing * VIEwFactory, and then call {@link #setFactory} on it to include your * Factory. *  * <p> * For performance reasons, vIEw inflation relIEs heavily on pre-processing of * XML files that is done at build time. Therefore, it is not currently possible * to use LayoutInflater with an XmlPullParser over a plain XML file at runtime; * it only works with an XmlPullParser returned from a compiled resource * (R.<em>something</em> file.) *  * @see Context#getSystemService */

大致的意思是:将 XML 布局实例化到相关的 Oject 中,可使用 Activity#getLayoutInflater() 或 Context#getSystemService 检索一个标准 inflater 实例,实例已经和 activity 或 context 挂钩,和正在运行的设备挂钩
inflater 高度依赖提前处理的 XML 文件,XML 文件在编译资源时就已经给出,所以目前不可能使用 LayoutInflater 在运行时动态使用 XmlPullParser 将未经加工的 XML 布局进行实例化

inflate():
参数1:xml 布局资源
参数2:父布局,指定生成布局的父布局,没有则生成布局作为 xml 布局的根布局

自定义控件:必须实现三个参数不同的构造函数
public XXX(Context context) {
super(context);
}

public XXX(Context context, AttributeSet attrs) {
super(context, attrs);
}

public XXX(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}

参考:bug_ _ android.view.InflateException: Binary XML file line #2: Error inflating class <unknown

总结

以上是内存溢出为你收集整理的Android 学习记录 - 动态加载布局全部内容,希望文章能够帮你解决Android 学习记录 - 动态加载布局所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/1109105.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-29
下一篇 2022-05-29

发表评论

登录后才能评论

评论列表(0条)

保存