I want to make a GridView in java, I don’t want to use an XML. The example below is an XML as a Layout. It shows 3 columns. I want to achieve that setting using Java only.
In my Activity, instead of GridView gv = (GridView) findViewById (R.id.gridview);
I use GridView gv = new GridView (this);.
Now my only problem is that it has only 1 column.
<?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>
The code equivalent to
android:numColumnsissetNumColumns(int). For things like id you’ll need to go back to View docs. Width and height will be set with LayoutParams .GridView Documentation on Android Developer.Com