I will try to give you a snippet, but to be honest, it makes no sense to use a GridView for your business, since all your elements are on screen anyway. You can create a LinearLayout pair in a small loop that will get the result.
I would advise you to set columnWidth in Runtime according to the width of the screen.
And your adapter must be provided with the column width and height to set them when inflating child views. And in this case you need to get rid of numColumns. Remember that using numColumns together with columnWidth does not really matter, especially if you want to fill the entire space. If you want to set numColumns, remove columnWidth.
Decision
Here is the result:
First we create our layout. In my case, this is the MainActivity layout and is called activity_main.xml . (Note that the GridView is missing because I will add this later in the code):
<RelativeLayout 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" tools:context=".MainActivity" > <TextView android:id="@+id/header" android:background="#444" android:gravity="center" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:textAppearance="?android:attr/textAppearanceLarge" android:textColor="@android:color/white" android:text="Dynamic Static GridView" /> <TextView android:id="@+id/footer" android:gravity="center" android:background="#444" android:textColor="@android:color/white" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:textAppearance="?android:attr/textAppearanceLarge" android:text="Shush" /> </RelativeLayout>
Our element of the GridView element is here in item_grid.xml :
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:background="#fff" android:layout_height="match_parent" > <TextView android:id="@+id/text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:textAppearance="?android:attr/textAppearanceLarge" /> </RelativeLayout>
Now the trick in MainActivity (I commented on the code you need to understand):
package com.example.dynamicstaticgridview;
import android.os.Bundle; import android.os.Handler; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.GridView; import android.widget.RelativeLayout; import android.app.Activity; import android.graphics.Color; public class MainActivity extends Activity { private static String items[];
COMMENTS : You better find the appropriate algorithm for choosing mCellWidth , mCellHeight , numberOfColumns and numberOfRows .
Sherif elkhatib
source share