如果您有固定数量的项目,并且希望它们一直延伸到屏幕末端,则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的尺寸并将其布置在屏幕上.
希望这可以帮助.