GridView is a ViewGroup that displays items in a two-dimensional, scrollable grid. The grid items are automatically inserted to the layout using a ListAdapter.
Same List view example you can use here just changing Listview to gridview.
For an introduction to how you can dynamically insert views using an adapter, read Building Layouts with an Adapter.
Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<GridView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/grid"
android:numColumns="auto_fit"/>
</LinearLayout>
Custom.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:textSize="30sp"
android:textColor="@color/colorPrimary">
</TextView>
MainActivity.java
package androiindians.gridbiew;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
GridView gridView;
ArrayAdapter adp;
String[] Courses={"Android","CoreJava","Adv Java"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gridView= (GridView) findViewById(R.id.grid);
adp=new ArrayAdapter(MainActivity.this,
R.layout.custom,Courses);
gridView.setAdapter(adp);
gridView.setOnItemClickListener(
new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(MainActivity.this,
"position="+position+" "+"id"+id, Toast.LENGTH_LONG).show();
}
});
}
}