您的位置:首页 > 其它

自定义GridView宽高设置问题,

2014-10-15 10:40 267 查看
当xml是这样:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView 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" >

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

<com.example.viewtest.RoomUserGridView
android:id="@+id/gridView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:background="#ffffff"
android:numColumns="4" />
</LinearLayout>

</ScrollView>这个是RoomUserGridView:
public class RoomUserGridView extends GridView {
int childHeight = 0;

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

public RoomUserGridView(Context context, AttributeSet attributeSet) {
super(context, attributeSet);
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
System.out.println("onMeasure " + widthMeasureSpec + " "
+ heightMeasureSpec);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}

@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
System.out.println("onLayout " + changed + " " + l + " " + t + " " + r
+ " " + b);
childHeight = b - t;
super.onLayout(changed, l, t, r, b);
}

}
MainActivity中gridView适配的时候:
gridView = (RoomUserGridView) findViewById(R.id.gridView);
List<Map<String, String>> data = new ArrayList<Map<String, String>>();
Map<String, String> map = new HashMap<String, String>();
map.put("name", "dss");
map.put("test", "dss1");

data.add(map);
data.add(map);
data.add(map);
data.add(map);
data.add(map);
data.add(map);
data.add(map);
gridView.setAdapter(new SimpleAdapter(MainActivity.this, data,
android.R.layout.simple_list_item_2, new String[] { "name",
"test" }, new int[] { android.R.id.text1,
android.R.id.text2 }));
这是运行结果,有两行gridview高度就只有一行:

所以设置gridView的高度,在MainActiviy,gridview.setAdapter后面添加以下代码:

LinearLayout.LayoutParams p = (android.widget.LinearLayout.LayoutParams) gridView
.getLayoutParams();
int w = View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED);
int h = View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED);
gridView.measure(w, h);
int height = gridView.getMeasuredHeight();
p.height = height * getLine(gridView.getCount());
gridView.setLayoutParams(p);<pre name="code" class="java">public int getLine(int count) {
if (count % 4 == 0) {
return count / 4;
} else {
return count / 4 + 1;
}
}


下面是运行结果:
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: