android - 在自定义 ViewGroup 上从布局 XML 扩充内容时,布局参数不适用

标签 android viewgroup layout-inflater android-inflate

我正在使用 LayoutInflater 将布局添加到自定义 ViewGroup(不是 ...Layout 的子类,而是一个简单的 ViewGroup)。

在与它进行了短暂的战斗之后,并实现了 this post 中所说的所有内容之后,我设法让内容最终出现,但由于某种原因,它并没有按照我想要的方式进行布局。在布局 XML 中,有 3 个元素需要水平分布,中心元素“插入”边缘的元素。

这是使布局膨胀的代码:

private LayoutInflater inf = null;
private Paint backpaint = null;
private ViewGroup inflated = null;

private void inflate(Context context) {
    this.setBackgroundColor(0x00000000);
    inf = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    inflated = (ViewGroup)inf.inflate(R.layout.application_heading, null);
    this.addView(inflated, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
}

@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
    inflated.measure(r, b);
    inflated.layout(l, t, r, b);
}

起初我只添加了 inflated.layout(l, t, r, b) 但它并没有真正起作用。在我添加了 inflated.measure(r,b) 之后,我终于看到了内容,但是它们都粘在一起了,就好像 LinearLayout 是基础膨胀的 XML 设置为 WRAP_CONTENT

我试图遍历 inflated ViewGroup 的子级并调用它们的 .layout(l,t,r,b),但这使它们拉伸(stretch)以填充整个布局,一个在另一个之上。

我一定是遗漏了一些非常小的东西。有人知道它可能是什么吗?

最佳答案

将包含类切换为 RelativeLayout 而不是 ViewGroup 的子类,一切都变得很美好。

关于android - 在自定义 ViewGroup 上从布局 XML 扩充内容时,布局参数不适用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9250901/

相关文章:

android - 获取当前位置

android - "cannot combine custom titles with other title features"和 "Source code does not match binarycode"

android - 如何从 Activity RootView 中删除 View

java - super.onCreate(savedInstanceState) 在第一次运行时崩溃

java - 在字符串中查找 JSON 对象

android - 单击 View 应在其 Canvas 上重绘

android - 如何将位图添加到 View ,然后将该 View 添加到 View 组

android - 以编程方式为 Android 布局充气

android - 如何在其他布局中 inflatedView ?

Android:使用 LayoutInflater 添加 View