GridView
GridView also works like ListView, only difference is that GridView is used to display grid of View objects.
The view class can be a Text view, an Image view or a view group which can be both an image and some text. Best example is view is phone gallery which shows images in a grid. We can set number of columns to a specific number as well as auto-fit the images into the columns.
Vertical or horizontal spacing between every single objects of gridView can be set by verticalSpacing and horizontalSpacing.
Using Adapter with GridView
Now adapter view is GridView and You can refer to the last tutorial for detailed explanations.
We will define a ListView in the main layout XML file activity_main.xml in the layout.
Let’s take an array of some amazing car brands.
String[] carBrands = { "Ferrari", "McLaren", "Jaguar", "Skoda", "Suzuki", "Hyundai", "Toyota", "Renault", "Mercedes", "BMW", "Ford", "Honda", "Chevrolet", "Volkswagon", };
As your Grid will have only text values, so we must define a TextView.
So now you need to create a new XML file, with name grid_item.xml in the layout folder, and add a TextView in it like this.
And the MainActivity.java file will look like this:
package com.example.myapplication; import androidx.appcompat.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.TextView; import android.widget.Toast; public class MainActivity extends AppCompatActivity { GridView gridView; TextView textView; String[] carBrands = { "Ferrari", "McLaren", "Jaguar", "Skoda", "Suzuki", "Hyundai", "Toyota", "Renault", "Mercedes", "BMW", "Ford", "Honda", "Chevrolet", "Volkswagon", }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); gridView = (GridView)findViewById(R.id.gridView); textView = (TextView)findViewById(R.id.showdata); final ArrayAdapter adapter = new ArrayAdapter(this, R.layout.grid_item, R.id.showdata, carBrands); gridView.setAdapter(adapter); gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView> adapterView, View view, int position, long l) { // TODO Auto-generated method stub /* appending I Love with car brand names */ String value = "I Love " + adapter.getItem(position); /* Display the Toast */ Toast.makeText(getApplicationContext(), value, Toast.LENGTH_SHORT).show(); } }); } }