Moataz Mahmoud
Moataz Mahmoud

Reputation: 39

implement gridview in activity android studio

Is it possible to implement gridView in an activity file and not an xml file because I want to create the number of grids dynamically.

GridView grid = new GridView();

doesn't work. thanks in advance

Upvotes: 1

Views: 164

Answers (1)

chornge
chornge

Reputation: 2111

Yes, it is possible; you were close, you just needed to pass in a context object:

GridView mGrid = new GridView(mContext);

option 1:

GridView mGrid = new GridView(this);

option 2:

GridView mGrid = new GridView(getContext());

and to set the columns dynamically, you pass in the number of columns to the gridview object you just created:

mGrid.setColumnWidth(numberOfColumns); //3, 4, 5, etc.

Here are two links from Android:

Upvotes: 1

Related Questions