android计算列表高度,Android List视图填充内容的高度

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

希望这可以帮助.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值