如果您有固定数量的项目并希望它们一直延伸到屏幕末尾,那么 ListView 并不是您的最佳选择。使用 LinearLayout 占据所有空间并将所有项目添加到其中。这是假设您希望这些项目每次都占据所有空间。
使用 LinearLayout,您可以均匀地分布项目,而无需自己进行任何计算。
LinearLayout linearLayout = new LinearLayout(getSupportActivity());
linearLayout.setOrientation(android.widget.LinearLayout.VERTICAL);
RelativeLayout.LayoutParams params = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT);
for (int i = 0; i < 5; i++) {
View individualView = new View(getSupportActivity());
// Create your custom view here and add it to the linear layout
// Leave the height as 0, LinearLayout will calculate the height properly.
params = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0);
additionalOption.setLayoutParams(params);
// As a we are adding it to the linear layout, they will all have a weight of 1, which will make them spread out evenly.
linearLayout.addView(additionalOption);
}
mainView.addView(linearLayout);
编辑:如果你已经用ListView实现了它并且更改它很麻烦,你可以执行以下操作。
确保列表视图宽度和高度在 xml 中设置为 match_parent。然后在创建自定义视图的适配器的 getView() 中,执行以下操作
// Get the height of the ListView
int totalHeight = listView.getHeight();
int rowHeight = totalHeight/getCount(); // Divide by number of items.
// Create custom view with the height calculated above.
请注意totalHeight 为0。如果您在onCreate() 中创建ListView 并在onCreate() 中设置适配器,则ListView 很可能尚未计算出宽度或高度。尝试在 onResume() 中设置适配器。此时,ListView 的尺寸已经计算出来并布置在屏幕上。
希望这可以帮助。