【发布时间】:2016-01-18 14:18:28
【问题描述】:
我有一个带有可变高度单元格的 GridView。我希望该行与该行中所有最大的单元格一样高。我可以将单元格高度调整为在一行上保持一致,但我无法设置 GridView 的高度并让它实际改变。
另一个问题是这个GridView在一个ScrollView中,所以有滚动条是不可能的。
这是一个问题,因为 GridView 确定整个 Grid 高度的方式是取第一个单元格并乘以行数。如果行可以有不同的高度,这是一个明显的问题。例如:
我尝试了很多方法来更新它,但我确信我错过了一些简单的东西。我正在尝试在 ViewTreeObserver 中进行更新,所以我知道 GridView 已经渲染,所以我的计算是正确的(它们是正确的)。代码:
ViewTreeObserver treeListener = mGridView.getViewTreeObserver();
treeListener.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@SuppressLint("NewApi")
@SuppressWarnings("deprecation")
@Override
public void onGlobalLayout() {
if(Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
mGridView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
else {
mGridView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
// Calculate the new height we want for the GridView
int newHeight = determineCellHeight(mGridView, mNumberOfColumns, mRows);
ViewGroup.LayoutParams params = mGridView.getLayoutParams();
params.height = newHeight;
mGridView.setLayoutParams(params);
// Have tried all of these too!!!
// mAdapter.notifyDataSetChanged();
// mGridView.requestLayout();
// mGridView.invalidateViews();
// mGridView.refreshDrawableState();
// mGridView.setLayoutParams(new LinearLayout.LayoutParams( LayoutParams.MATCH_PARENT, newHeight + 10));
// mGridView.setLayoutParams(new LinearLayout.LayoutParams( LayoutParams.MATCH_PARENT, newHeight + 10));
// View lastChild = mGridView.getChildAt( mGridView.getChildCount() - 1 );
// mGridView.setLayoutParams( new LinearLayout.LayoutParams( LayoutParams.MATCH_PARENT, lastChild.getBottom() ) );
// mAdapter.notifyDataSetChanged();
// mGridView.invalidateViews();
// mGridView.setMinimumHeight(newHeight);
// mGridView.requestLayout();
// mGridView.refreshDrawableState();
}
});
我开始怀疑这是否可能,尽管众多 Stackflows 似乎表明它是...
【问题讨论】: