2

我想在 java 中制作一个GridView,我不想使用 XML。下面的示例是一个作为布局的 XML。它显示 3 列。我想仅使用 Java 来实现该设置。

在我的活动中,而不是GridView gv = (GridView) findViewById (R.id.gridview);

我用GridView gv = new GridView (this);.

现在我唯一的问题它只有 1 列

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

<GridView
    android:id="@+id/gridview"
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"
    android:columnWidth="90dp"
    android:numColumns="auto_fit"
    android:verticalSpacing="10dp"
    android:horizontalSpacing="10dp"
    android:stretchMode="columnWidth"
    android:gravity="center"/>

</LinearLayout>
4

2 回答 2

2

等效于的代码android:numColumnssetNumColumns(int)。对于像 id 这样的事情,您需要返回查看文档。宽度和高度将使用 LayoutParams 设置。

Android Developer.Com 上的GridView 文档

于 2012-09-18T12:37:27.307 回答
2

试试这个。

GridView gv = new GridView(context);
gv.setId(999999);
gv.setLayoutParams(new    
GridView.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT));
gv.setBackgroundColor(Color.GREEN);
gv.setNumColumns(3);
gv.setColumnWidth(GridView.AUTO_FIT);
gv.setVerticalSpacing(5);
gv.setHorizontalSpacing(5);
gv.setStretchMode(GridView.STRETCH_COLUMN_WIDTH);
gv.setGravity(Gravity.CENTER);
于 2012-09-18T13:04:36.813 回答