安卓系统中使用LayoutInflater要注意的一些坑

  

  

在平时的开发过程中,我们经常会用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);      

视觉上的结果都是一样的

  

 Android中使用LayoutInflater要注意的一些坑”> <br/>
  </p>
  <p>但是日志就有一点不一样了,这就是attachToRoot不同的值所导致的。</p>
  <p>第一种方法的日志<br/>
  </p>
  
  <pre类=   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);      

 Android中使用LayoutInflater要注意的一些坑

  

此时再看看它的布局文件:

        & 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要注意的一些坑