您的位置:首页 > 其它

GridView简单使用

2015-10-19 09:48 239 查看
如图是效果图

[b]今天看到看到这个代码发现一个问题 就是我的listView的布局不对 我的GridView的 android:layout_height="wrap_content"这样[/b]

[b]写会导致getView()方法被重复调用了[/b]

[b]这是什么样的情况了,看了网上的资料以后我知道原来没有设置器listview 的布局方式不是fill-parent,[/b]

[b]而是wrap-content,会计算父控件的高度所以造成了一种反复调用情况,从而次数不确定。[/b]

而为什么会有很多组次调用呢?

问题就在于在layout中的决定ListView或者它的父元素的height和width属性的定义了。fill_parent会好一点,计算 方法会比较简单,只要跟父元素的大小相似就行,但是即使是fill_parent,也不能给View当饭吃,还是要计算出来具体的dip,所以 measure还是会被调用,只是可能比wrap_content的少一点。至于自适应的它会一直考量它的宽和高,根据内容(也就是它的子Item)计算 宽高。可能这个measure过程会反复执行,如果父元素也是wrap_content,这个过程会更加漫长。

所以,解决方法就是尽量避免自适应,除非是万不得已,固定大小或者填充的效果会比较好一些。

package org.xml.demo;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.GridView;

public class MyGridView extends GridView {

public MyGridView(Context context, AttributeSet attrs) {
super(context, attrs);
}

public MyGridView(Context context) {
super(context);
}

public MyGridView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}

@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,
MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, expandSpec);
}

}


View Code

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#eee"
android:orientation="vertical" >

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="15dp"
android:gravity="center_vertical"
android:paddingBottom="4dp"
android:paddingTop="5dp"
android:text="所有产品"
android:textSize="15sp" />

<View
android:layout_width="fill_parent"
android:layout_height="1dp"
android:background="@android:color/white" />

<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content" >

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >

<org.xml.demo.MyGridView
android:id="@+id/product"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:horizontalSpacing="5dp"
android:numColumns="2"
android:paddingBottom="10dp"
android:paddingLeft="7dp"
android:paddingRight="7dp"
android:paddingTop="5dp"
android:verticalSpacing="8dp" />
</LinearLayout>
</ScrollView>

</LinearLayout>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: