在平时的开发过程中,我们经常会用LayoutInflater这个类,比如说在<代码>片段美元onCreateView 代码>和<代码> RecyclerView.Adapter美元onCreateViewHolder> 代码中都会用的到。它的用法也无非就是<代码> LayoutInflater。充气(resourceId、根、attachToRoot)> 代码,第一个参数没什么好说的,但第二个和第三个参数结合起来会带来一定的迷惑性。之前有时候会发现界面布局上出了一些问题,查了很久之后偶然的改动了这两个参数,发现问题解决了,然后也就过去了,并没有去思考这是为什么,然后下次可能又重复这种困境了。
所以想在这里总结一下,避免以后继续掉坑。
/* * *增加一个新的视图层次结构从指定的xml资源。抛出 * {@link InflateException}如果有一个错误。 * * @param XML布局资源加载资源ID(例如, * & lt; code> R.layout.main_page) * @param根可选视图的父(如果生成的层次结构 * & lt; em> attachToRoot</em>是正确的),或者其他简单的对象 *提供了一组LayoutParams根返回的值 *层次结构(如果& lt; em> attachToRoot</em>是假的。) * @param attachToRoot是否应该高度膨胀的层次结构 *根参数# 63;如果错误,根> & lt; & # 63; xml version=" 1.0 " encoding=" utf - 8 " & # 63;比; & lt; TextView xmlns: android=" http://schemas.android.com/apk/res/android " android: id=癅 + id/item_text” android: layout_width=" 200 dp” android: layout_height=" 50 dp” android: layout_marginLeft=" 16 dp " android: layout_marginTop=" 16 dp " android:背景=" @color/colorAccent” android:重力="中心" android:文本=暗テ?文本”/祝辞
正常的情况
//第一种方法 视图inflatedView=LayoutInflater.from(这).inflate (R.layout.item_text mLinearLayout,真的); 日志。d(标签”,膨胀的观点是“+ inflatedView);//第二种方法 视图inflatedView=LayoutInflater.from(这).inflate (R.layout.item_text mLinearLayout,假); 日志。d(标签”,膨胀的观点是“+ inflatedView); mLinearLayout.addView (inflatedView);
视觉上的结果都是一样的
D/MainActivity:膨胀的观点是android.widget。LinearLayout {36 e9aac方法…………我。0 0 - 0 0 # 7 f0c0051应用:id/线性}
第二种方法的日志
D/MainActivity:膨胀的观点是android.support.v7.widget。AppCompatTextView {3 c9d37b诉.....……ID 0 0 - 0 0 # 7 f0c0054应用:ID/item_text}
如果在第一种方法的基础上再加上<代码> mLinearLayout.addView (inflatedView)> 代码就会造成报错
<代码> IllegalStateException:指定的子已经有一个父....> 代码,.
而如果第二种方法没有这句话,界面上是看不到任何东西的。
mLinearLayout=(LinearLayout) findViewById (R.id.linear); 视图inflatedView=LayoutInflater.from(这).inflate (R.layout.item_text, null); 日志。d(标签”,膨胀的观点是“+ inflatedView); mLinearLayout.addView (inflatedView);
此时再看看它的布局文件:
& lt; & # 63; xml version=" 1.0 " encoding=" utf - 8 " & # 63;比; & lt; TextView xmlns: android=" http://schemas.android.com/apk/res/android " android: id=癅 + id/item_text” android: layout_width=" 200 dp” android: layout_height=" 50 dp” android: layout_marginLeft=" 16 dp " android: layout_marginTop=" 16 dp " android:背景=" @color/colorAccent” android:重力="中心" android:文本=暗テ?文本”/祝辞
不难发现,所有layout_xxx的属性全都失效了。
上面说了,在创建布局的时候,要把布局添加到根中去,并且有两种方法,但是我们在onCreateViewHolder中添加布局的时候却是这样写的:
@Override 公共MyViewHolder> 爪哇. 朗。IllegalStateException:指定的孩子已经有了父母。安卓系统中使用LayoutInflater要注意的一些坑