未经本人授权,不得转载!否则必将维权到底
出了个 Bug,GridView 作为 ListView 头布局,里面有五个 Item,每行三个,应该展示两行才对。但是现在只展示了三个 Item ,其他的要通过滚动条滑动才能可见,而 GridView 是头布局,滚动条根本无法滑动,所以下面的两个 Item 不可见。
一、问题展示:

二、修复方案,自定义一个GridView ,动态计算高度,可完美解决嵌套问题(ListView 嵌套问题也是同样的解决方法):
import android.content.Context;
import android.util.AttributeSet;
import android.widget.GridView;
/**
* Created by KeithXiaoY on 2017/6/7.
* 让GridView的高度为Wrap_content
*/
public class MyGridView extends GridView {
public MyGridView(Context context) {
super(context);
}
public MyGridView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MyGridView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int heightSpec;
if (getLayoutParams().height == LayoutParams.WRAP_CONTENT) {
// The great Android "hackatlon", the love, the magic.
// The two leftmost bits in the height measure spec have
// a special meaning, hence we can't use them to describe height.
heightSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,MeasureSpec.AT_MOST);
} else {
heightSpec = heightMeasureSpec;
}
super.onMeasure(widthMeasureSpec, heightSpec);
}
}
三、修复结果:

本文参考:
Stackoverflow——Set Fixed GridView Row Height

网友评论