所以我有一个可扩展视图的网格视图(用户点击它们,它们可以动画扩展)。问题是,当我点击第二列时,我的gridview只会增加行高。在第一张图片中,您可以看到我按下列表中的第一个项目并进行了扩展,但gridview没有更新其行的高度。在第二张图片中,我点击了第二列中的第二个项目,并且网格视图按预期展开。看来gridview只是根据第二列进行测量。如何将它与第一列进行比较并选择较大的一列?感谢。
编辑: 这甚至发生在简单的布局上。行宽始终是第二列的高度,即使该行中的第一列更高。
答案 0 :(得分:2)
我遇到了同样的问题,为了解决这个问题,我不得不扩展GridView并使用一些脏黑客......
public class AutoGridView extends GridView {
public AutoGridView(Context context, AttributeSet attrs, int defStyle){
super(context, attrs, defStyle);
}
public AutoGridView(Context context, AttributeSet attrs){
super(context, attrs);
}
public AutoGridView(Context context){
super(context);
}
@Override
protected void layoutChildren(){
/*This method is called during onLayout. I let the superclass make the hard
part, then I change the top and bottom of visible items according to their
actual height and that of their siblings*/
final int childrenCount = getChildCount();
if(childrenCount <= 0){ //nothing to do, just call the super implementation
super.layoutChildren();
return;
}
/*GridView uses the bottom of the last child to decide if and how to scroll.
UGLY HACK: ensure the last child bottom is equal to the lowest one.
Since super implementation might invalidate layout I must be sure the old
value is restored after the call*/
View v = getChildAt(childrenCount - 1);
int oldBottom = v.getBottom();
super.layoutChildren();
v.setBottom(oldBottom);
for(int i = 0; i < getNumColumns(); ++i){
int top = getListPaddingTop();
for(int j = i; j < childrenCount; j += getNumColumns()){
v = getChildAt(j);
/*after setTop v.getHeight() returns a different value,
that's why I'm saving it...*/
int viewHeight = v.getHeight();
v.setTop(top);
top += viewHeight;
v.setBottom(top);
top += getVerticalSpacing();
}
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec){
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
final int childrenCount = getChildCount();
if(getAdapter() != null && childrenCount > 0){
measureChildren(widthMeasureSpec, heightMeasureSpec);
int width = getSize(widthMeasureSpec);
int heightSize = getSize(heightMeasureSpec);
int heightMode = getMode(heightMeasureSpec);
int maxHeight = heightSize;
for(int i = 0; i < getNumColumns(); ++i){
int columnHeight = 0;
for(int j = i; j < childrenCount; j += getNumColumns())
columnHeight += getChildAt(j).getMeasuredHeight() + getVerticalSpacing();
maxHeight = Math.max(maxHeight, columnHeight);
}
getChildAt(childrenCount-1).setBottom(maxHeight); // for the scrolling hack
int height = heightSize;
if(heightMode == UNSPECIFIED)
height = maxHeight;
else if(heightMode == AT_MOST)
height = Math.min(maxHeight, heightSize);
setMeasuredDimension(width, height);
}
}
}
我知道,可能对你来说这个答案为时已晚,但我希望它可以帮助那些像我一样绊倒你问题的人^^