【发布时间】:2016-10-11 11:18:58
【问题描述】:
几个月前,我成功编写了代码来调整 gridView 的大小,以适应每次加载新数据表时所需的行数。我刚刚注意到这不再起作用,我不知道为什么。据我所知,所有发生的变化是我已经升级了 SDK。下面是用于动态调整gridView大小的代码。
/**
* create a resizable gridView by utilizing the onLayoutChanged system method
* @param items an arrayList containing the items to be read into each cell
*/
public void createGridView(ArrayList<String> items)
{
Log.d(TAG, "createGridView(): ");
gridView.setAdapter(new GridAdapter(items));
gridView.addOnLayoutChangeListener(new View.OnLayoutChangeListener(){
@Override
public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
Log.d(TAG, "onLayoutChange(): ");
currentGridHeight = gridView.getHeight();
if (singleGridHeight == 0){
singleGridHeight = currentGridHeight/currentGridRows;
}
// fix for nestedScrollView automatically scrolling to the bottom after swipe
nestedScrollView.scrollTo(0, 0);
}
});
}
/**
* re-sizes the height of the gridView based on the amount of rows to be added
* @param gridView
* @param items
* @param columns
*/
private static void resizeGridView(GridView gridView, int items, int columns) {
Log.d(TAG, "resizeGridView(): ");
ViewGroup.LayoutParams params = gridView.getLayoutParams();
params.height = singleGridHeight * items;
gridView.setLayoutParams(params);
gridView.requestLayout();
}
// gridView adapter
private static final class GridAdapter extends BaseAdapter {
final ArrayList<String> mItems;
final int mCount;
/**
* Default constructor
*
* @param items to fill data to
*/
private GridAdapter(final ArrayList<String> items) {
// create arrayList full of data called "items"
// ..
// ..
// resizing the gridView based on the number of rows
currentGridRows = items.size();
// if this isn't the very first gridView then resize it to fit the rows
if (currentGridHeight != 0){
resizeGridView(gridView,items.size(),6);
}
}
当 gridView 首次创建(加载的第一个表)时,我测量 gridView 的高度并将其除以行数以确定每行所需的高度。当我加载后续的 gridViews 时,我通过将此高度乘以行数来调整它们的大小。
这不再有效。后续的 gridViews 仍然大致只能容纳一行。
有什么想法吗?
编辑:它似乎将 singleRowHeight 计算为 9dp,而实际上每行需要大约 64dp。
【问题讨论】:
标签: android android-layout gridview android-view