【问题标题】:Change child views to fit parent's width when added dynamically动态添加时更改子视图以适应父级的宽度
【发布时间】:2013-05-02 22:02:13
【问题描述】:

我有一个自定义视图,可以动态添加子视图。

添加每个孩子后,我需要重新计算视图的大小,以便它们适合父母的宽度

例如: 如果我有一个 TextView:

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:gravity="center"
android:padding="8dp"
android:clickable="true"
android:textColor="#666666"
android:visibility="visible"/>

如果我将其中三个添加到 xml 中的水平 LinearLayout 中,它会正确调整三个视图的大小,以便总宽度与父视图匹配。

但我想一次膨胀一个并添加它们,以便在布局中需要不同数量的 TextView 时可以在代码的其他地方重用。

当我这样做时,总宽度小于其父级,并且在添加新视图时我无法调整视图大小。

这是我放大视图的地方:

layout = (LinearLayout) inflater.inflate(R.layout.segmented_control, this); 
TextView item = (TextView) inflater.inflate(R.layout.segmented_control_item, null);

【问题讨论】:

  • 向我们展示您膨胀视图的代码。还要确保在创建它们时将父视图传递给 LayoutInflater。

标签: android view android-linearlayout


【解决方案1】:

将宽度更改为match_parent,我认为您需要保留weight。将父布局传递给充气器。

layout = (LinearLayout) inflater.inflate(R.layout.segmented_control, this); 
TextView item = (TextView) inflater.inflate(R.layout.segmented_control_item, layout, false);
layout.addChild(item);

我不确定这是否能立即生效,您可能需要对布局参数进行一些试验。

【讨论】:

  • 非常感谢,将宽度更改为 match_parent,保持重量并将父布局传递给充气机工作 :)
【解决方案2】:

将您的 TextView 布局宽度更改为 fill_parent 并移除权重。我认为它应该有效。

【讨论】:

  • 移除权重会导致最后一个 TextView 跨越整个宽度,因此无法看到其他 TextView。上面的解决方案完全符合我的要求。感谢您的回复:)
猜你喜欢
  • 2013-11-01
  • 1970-01-01
  • 2013-12-18
  • 2013-10-28
  • 2017-07-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-01
相关资源
最近更新 更多