其他分享
首页 > 其他分享> > Android 学习记录 - 动态加载布局

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

作者:互联网

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

标签:XML,LayoutInflater,布局,inflater,context,Context,Android,动态,加载
来源: https://blog.csdn.net/qq_43323826/article/details/99831580