重新审视LayoutInflater的意义

时间:2016-01-22 10:31:35

标签: android android-layout android-inflate

已经有一个问题here,其标题为理解LayoutInflater ,其中@andig的解释非常好,可以接受。但有一件事困扰我的是当在充气期间没有指定父级并且在addView中没有指定高度/宽度时addView的行为。以下是由@andig发布的代码: -

主要布局(main.xml)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
</LinearLayout>

子布局(red.xml)

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="25dp"
    android:layout_height="25dp"
    android:background="#ff0000"
    android:text="red" />

带有layoutinflator的活动代码

public class InflaterTest extends Activity {

    private View view;

    @Override
    public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);

      setContentView(R.layout.main);
      ViewGroup parent = (ViewGroup) findViewById(R.id.container);

      // result: layout_height=wrap_content layout_width=match_parent
      view = LayoutInflater.from(this).inflate(R.layout.red, null);
      parent.addView(view);

      // result: layout_height=100 layout_width=100
      view = LayoutInflater.from(this).inflate(R.layout.red, null);
      parent.addView(view, 100, 100);

      // result: layout_height=25dp layout_width=25dp
      // view=textView due to attachRoot=false
      view = LayoutInflater.from(this).inflate(R.layout.red, parent, false);
      parent.addView(view);

      // result: layout_height=25dp layout_width=25dp 
      // parent.addView not necessary as this is already done by attachRoot=true
      // view=root due to parent supplied as hierarchy root and attachRoot=true
      view = LayoutInflater.from(this).inflate(R.layout.red, parent, true);
    }
}

案例困扰是在注释 //结果:layout_height = wrap_content layout_width = match_parent 下面输入的代码。我检查了代码,发现在inflating期间没有指定父级,子级布局参数被忽略,并且通过解释,它应该采用将子布局添加到的父/ root。

但是当我执行并运行此代码时,尽管父/ root(main.xml)指定了layout_height为match_parent,但layout_height被认为是wrap_content,但宽度被认为是正确的,即match_parent。

我使用android os 4.0.4在设备上运行它。

所以问题是,这是某种类型的错误,或者当你没有指定任何布局参数和root时,考虑到layout_height的膨胀是wrap_content。

0 个答案:

没有答案