LayoutInflater忽略了参数?

7
我有一个代表ImageButton的XML对象,如下所示:
<?xml version="1.0" encoding="utf-8"?>
<ImageButton
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@+id/genreCellItemId" android:layout_weight="1"
  android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center"
  android:paddingLeft="5.0dip" android:paddingRight="5.0dip">
</ImageButton>

我尝试使用以下代码将其填充并添加到TableRow中:

LayoutInflater inflater= this.getLayoutInflater();
TableLayout grid = (TableLayout)findViewById(R.id.bodyTableLayout);
TableRow row = (TableRow)inflater.inflate(R.layout.genre_row, null);
View myButton = (View)inflater.inflate(R.layout.genre_cell, null);
row.addView(tempButton, new TableRow.LayoutParams());
grid.addView(row, new TableLayout.LayoutParams());

好的,我注意到它看起来不像预期的那样,所以我启动了Hierarchy Viewer并注意到ImageButton实际上具有layout_width = FILL_PARENT而不是WRAP_CONTENT,而且layout_gravity为NONE,也没有看到任何填充...

那么,我是错误地膨胀它吗?还是可能是新的TableRow.LayoutParams()部分做错了什么?

3个回答

18

尝试使用 inflate(R.layout.genre_cell, row, false) 代替 inflate(R.layout.genre_cell, null),看看是否有帮助。有时候,当膨胀视图知道被膨胀的视图将要进入什么样的父级元素时,膨胀效果会更好。


不幸的是,那个方法没有起作用。 仍然看不到填充,并且按钮仍然“粘”在一起。 当使用层次结构查看器时,layout_width仍然是fill_parent,而gravity是none。我在膨胀ImageButton之后设置了一个背景,这可能是问题吗?此外,新的LayoutParams()是否有问题? - TiGer
我注意到我的TableRow也没有被正确地填充:<TableRow xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/genreRowItemId" android:layout_height="wrap_content" android:layout_width="fill_parent" android:paddingBottom="5dp" android:paddingTop="5dp" android:gravity="center"> </TableRow>这个也没有设置它的layout_gravity为Center,而是保持在NONE。 - TiGer
看起来你可能在错误地膨胀所有内容。LayoutParams 无法在不知道父级上下文的情况下进行膨胀。在膨胀期间没有(空)根(父级)意味着没有布局/边距膨胀。 - WORMSS
在我的情况下,我将充气视图内容设置为“PopupWindow”,因此“PopupWindow”不是“View Group”,我无法在充气时将其用作。我面临的问题是,充气的视图忽略了其父LinearLayout的填充。 - Muhammad Babar

2

经过将近两天的努力,我终于找到了罪魁祸首:

正如我所怀疑的那样,如果您已经在XML声明中“格式化”了您的视图,那么新的LayoutParams()就会成为一个问题......因此,在不考虑新的LayoutParams()的情况下,我的表格可以正常显示......

所以只需使用:

grid.addView(row);

嗨,我正在从XML中膨胀我的视图并在弹出窗口中显示它,但它缺少其父级填充。 - Muhammad Babar

1
对于那些使用Data Binding x Kotlin并遇到此问题的人:

请使用以下替代方法:

val binding = YourBindingClass.inflate(LayoutInflater.from(parent.context))
return ViewHolder(binding)

请使用这个:
val binding = YourBindingClass.inflate(LayoutInflater.from(parent.context), parent, false)
return ViewHolder(binding)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接