Android 解决 GridView 嵌套 ScrollView / ListView 条目展示不全的问题

未经本人授权,不得转载!否则必将维权到底

出了个 Bug,GridView 作为 ListView 头布局,里面有五个 Item,每行三个,应该展示两行才对。但是现在只展示了三个 Item ,其他的要通过滚动条滑动才能可见,而 GridView 是头布局,滚动条根本无法滑动,所以下面的两个 Item 不可见。

一、问题展示:

问题展示.png

二、修复方案,自定义一个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);
    }
}

三、修复结果:

修复后效果.png

本文参考:

Stackoverflow——Set Fixed GridView Row Height


本文原创发布于微信公众号「keithxiaoy」,编程、思维、成长、正能量,关注并回复「编程」、「阅读」、「Java」、「Python」等关键字获取免费学习资料

不要给自己的人生设限

猜你喜欢

转载自blog.csdn.net/xiaoy_yan/article/details/80985876