This tutorial shows how to display a String list in a GridView.
Step 1: Create a new project with name GridView and package name com.myexample.gridview. Select File/New/New Project. Fill the forms and click “Finish” button.
Step 2: Open res/layout/xml (or) main.xml and add following code. Here we add a GridView mainGridView1.
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" xmlns:ads="http://schemas.android.com/apk/res-auto" tools:context=".MainActivity" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <GridView android:layout_height="wrap_content" android:layout_width="wrap_content" android:numColumns="3" android:id="@+id/mainGridView1"/> </LinearLayout>
Step 3: Open app/src/main/java/package and open MainActivity.java. Add following code in it. Here we create a String list and set an adapter to display this String list in GridView.
package com.myexample.gridview; import android.app.*; import android.os.*; import android.view.*; import android.view.View.*; import android.widget.*; import java.util.*; public class MainActivity extends Activity { private GridView gridview1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); gridview1 = (GridView) findViewById(R.id.mainGridView1); final String[] stringlist = {"item 1", "item 2", "item 3", "item 4", "item 5" , "item 6", "item 7", "item 8", "item 8"}; gridview1.setOnItemClickListener(new GridView.OnItemClickListener(){ @Override public void onItemClick(AdapterView<?> p1, View p2, int p3, long p4){ Toast.makeText(getApplicationContext(), stringlist[p3], Toast.LENGTH_LONG).show(); } }); ArrayAdapter<String> adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, stringlist); gridview1.setAdapter(adapter); } }
Output:
Now run the app. The app will display String list in a GridView.