昨晚上 ,写了一个Gridview 显示旅游的图片,但是 不知道为什么 只能显示一行图片,而且我的图片数量超过单行的数量,而且我的高度也写的wrap_content ,按道理来说应该有多少显示多少呀,后来问了一下朋友,GridView 高度应该给一个固定值,跟ListView一样 ,好吧,,,,那高度也不能直接写死啊,那就需要写一个自定义的Gridview 来测量高度了。。。。
废话不多说,上代码。代码里有注释
/** * Created by ChenHe on 2016/8/19. */ public class MyGridView extends GridView { public boolean hasScrollBar = true; public MyGridView(Context context) { this(context, null); } public MyGridView(Context context, AttributeSet attrs) { super(context, attrs, 0); } public MyGridView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int expandSpec = heightMeasureSpec; if (hasScrollBar) { expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST); super.onMeasure(widthMeasureSpec, expandSpec);// 注意这里,这里的意思是直接测量出GridView的高度 } else { super.onMeasure(widthMeasureSpec, heightMeasureSpec); } } }
这样就OK了
附上Gridview一些属性
九宫格 android:stretchMode="columnWidth",缩放与列宽大小同步
<GridView
|
android:layout_height="wrap_content"
android:layout_height="wrap_content"