【问题标题】:Inflated layout behaves differently than static XML layout膨胀布局的行为与静态 XML 布局不同
【发布时间】:2011-10-16 19:46:21
【问题描述】:

我有一个用作父布局模板的布局。根据我启动的活动,我想在父模板中使用膨胀视图填充 LinearLayout 的内容。现在,如果我将父布局和子布局放到同一个 XML 文件中,一切看起来都不错。但是如果我在父布局上使用 setContentView() ,然后膨胀子视图并将其添加到父布局中的同一位置,事情就不起作用了。我放入子视图的 LinearLayout 和作为子视图根的 LinearLayout 都有 android:layout_height="fill_parent",但子视图无法填充它添加到的 LinearLayout。

有什么明显的我做得不对吗?请记住,这些布局应该看起来相同,只有一种方法是静态的,另一种是动态的。我认为这与正在计算的父布局尺寸有关,并且在子视图膨胀后没有更新。

谢谢!

【问题讨论】:

    标签: android


    【解决方案1】:

    好的,我想通了。

    当你给孩子充气时,你需要将孩子的父视图传递给充气机,以便充气机知道要让它有多大。我使用 null 父级进行膨胀,然后将子级添加到父级,但这导致子级表现得好像我将布局参数设置为“wrap_content”。

    不正确:

    ViewGroup parent = (ViewGroup) root.findViewById(R.id.parent);
    parent.removeAllViews();
    LinearLayout child;
    child = (LinearLayout) inflater.inflate(R.layout.child, null);
    parent.addView(child);
    

    正确:

    ViewGroup parent = (ViewGroup) root.findViewById(R.id.parent);
    parent.removeAllViews();
    (LinearLayout) inflater.inflate(R.layout.child, parent);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多