我找不到裁剪问题的解决方案,所以我向 ListView 添加了页眉和页脚。我将 ListView 的高度改回 match_parent,然后,使用 ListView 父视图上的 post 方法,我能够计算出页眉和页脚的高度,如下所示:
// this call should be included in the onCreate method
// the post method is called after parentView is ready to be added
// so the parentView's height and width can be used
parentView.post(addSpace(parentView, myListView));
private Runnable addSpace(final RelativeLayout parent, final ListView list) {
return new Runnable(){
public void run() {
// create list adapter here or in the onCreate method
// R.layout.list_item refers to my custom xml layout file
adapter = new ArrayAdapter<String>(MainActivity.this, R.layout.list_item, values);
// calculate size and add header and footer BEFORE applying adapter
// listItemHeight was calculated previously
spacerSize = (parent.getHeight()/2) - (listItemHeight/2);
list.addHeaderView(getSpacer(), null, false);
list.addFooterView(getSpacer(), null, false);
list.setAdapter(adapter);
}
}
}
// I used a function to create my spacers
private LinearLayout getSpacer(){
// I used padding instead of LayoutParams thinking it would be easier to
// change in the future. It wasn't, but still made resizing my spacer easy
LinearLayout spacer = new LinearLayout(MainActivity.this);
spacer.setOrientation(LinearLayout.HORIZONTAL);
spacer.setPadding(parentView.getWidth(), spacerSize, 0, 0);
return spacer;
}
使用这种方法,我能够在我的 ListView 的顶部和底部添加适当的间距,因此当我一直滚动到顶部时,顶部项目出现在我的视图中心。
问题:我的应用程序允许用户隐藏底部界面元素,这应该使我的父母更高。我正在想办法让我的页眉和页脚动态变高,但我可能需要简单地删除 ListView 并使用更大的页眉和页脚重新创建它。
我希望这可以帮助某人摆脱数小时的沮丧:)