Stella
Stella

Reputation: 3933

In Android Programming, How to make a GridView in Java without using XML?

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>

Upvotes: 2

Views: 2125

Answers (2)

Hemant
Hemant

Reputation: 759

Try This.

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);

Upvotes: 2

Chirag
Chirag

Reputation: 56925

The code equivalent to android:numColumns is setNumColumns(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

Upvotes: 2

Related Questions