This article will demonstrate how to build an application showcasing the utilization of CustomArrayAdapters in a GridView. GridViews are containers that exhibit views in two dimensions (rows and columns) and are commonly employed in Android applications, such as in a gallery app. The adapter serves as a bridge connecting the UI elements with the data source, facilitating data population without explicit instructions. For instance, in a gallery app, as the user scrolls through, the GridView dynamically populates the content.
CustomArrayAdaptersGridViewAndroid already provides an ArrayAdapter implementation, which can be easily utilized with a single line of code, as shown below. Custom ArrayAdapters come into play when dealing with lists of single items, such as phone contacts, countries, or names. Below is the syntax of using ArrayAdapter for displaying text data.
Syntax:Parameters:The ArrayAdapter method has limitations, particularly when dealing with complex layouts. For instance, in scenarios like developing apps similar to Netflix or Amazon Prime, where each element comprises multiple components like ImageView, TextView, etc., the ArrayAdapter falls short. To address this limitation, a custom Adapter needs to be created by extending the ArrayAdapter class.
The following code snippet illustrates the structure of a Custom ArrayAdapter:
import android.content.Context; |
import android.view.View; |
import android.view.ViewGroup; |
import android.widget.ArrayAdapter; |
import java.util.List; |
The CustomAdapter class extends the ArrayAdapter class and overrides certain methods to customize the behavior of the Adapter.
A sample GIF provided below illustrates the implementation of the project using Java and Kotlin Programming Language for Android.
Java and Kotlin Programming Language for Android.
To start a new project in Android Studio, follow the steps outlined in creating a project using Java or Kotlin programming languages for Android.
Begin by accessing the activity_main.xml file, which serves as the user interface (UI) for the project. Below is the code snippet for the activity_main.xml file with explanatory comments.
Generate a new file named custom_view.xml within the same directory as the activity_main.xml file. This Custom View will contain an ImageView and a TextView.
LinearLayout
android:orientation
wrap_content
tools:srcCompat="@tools:sample/avatars"
@ id/imageView
@ id/textView
Now, in order to store the information of our custom view effectively, we create a getter-setter class. While it's possible to manage with arrays for images and text, if we wish to incorporate additional elements like a Button, a third array would be necessary. Therefore, a dedicated class for the custom view offers more versatility. Below is the code for the 'items' file:
public class items {
private int image_id;
private String text;
getImage_id() { }
setImage_id(int image_id) { }
getText() { }
setText(String text) { }
items(int img, String text) { }
Class Structure:
items
contains an internal constructor with parameters image_id
and text
.Functions in the Class:
getImage_id()
function returns the image ID of the item.setImage_id()
function sets the image ID for the item.getText()
function returns the text of the item.setText()
function sets the text for the item.Note: For an image, the class stores the ID of the image and not the actual image.
Create a new class named CustomAdapter
in the same directory as the items
class. The primary method within the adapter class is getView()
.
getView() Method:
The getView()
method is responsible for inflating the layout, setting data to views, and returning the view.
Code Snippet:
import android.content.Context; | import android.view.LayoutInflater; | import android.view.View; | import android.view.ViewGroup; | import android.widget.ImageView; | import android.widget.TextView; | import androidx.annotation.NonNull; | import androidx.annotation.Nullable; |
@NonNull @Override | public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { | ||||||
View v = convertView; if (v == null) { // Inflate the main layout LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); v = inflater.inflate(custom_layout_id, null); } // Initialize views ImageView imageView = v.findViewById(R.id.imageView); TextView textView = v.findViewById(R.id.textView); // Set data to views items item = items_list.get(position); imageView.setImageResource(item.getImage_id()); textView.setText(item.getText()); return v; |
android.view.LayoutInflater
: Responsible for instantiating layout XML file into its corresponding View objects.android.widget.ImageView
: Displays images within the user interface.android.widget.TextView
: Displays text data in the user interface.getView
function is essential for populating items in a ListView or GridView.In Android, the getView
function is commonly implemented as follows:
fun getView(position: Int, convertView: View?, parent: ViewGroup): View { var v = convertView if (v == null) { val inflater = getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater v = inflater.inflate(custom_layout_id, null) } val imageView = v!!.findViewById(R.id.imageView) val textView = v.findViewById(R.id.textView) val item: items = items_list.get(position) imageView.setImageResource(item.getImage_id()) textView.setText(item.getText()) return v}
getView
is called, it checks if a View
object is available for reuse.View
hierarchy from the specified XML layout resource.ImageView
and TextView
are then initialized and populated with data.LayoutInflater
is essential for dynamically creating View objects from XML layouts.LayoutInflater
, developers can efficiently populate ListView items.Remember, proper understanding of Android view inflation is crucial for effective UI development in Android apps.
Inflate a new view hierarchy from the specified xml resource. Throws InflateException if there is an error. |
root ViewGroup: Optional view to be the parent of the generated hierarchy. This value may be null. |
A CustomAdapter in Android is a class that extends the ArrayAdapter class and is used to provide custom layouts for items in a ListView or Spinner.
It allows developers to customize the appearance of individual items in a list-based user interface component.
For instance, in a music app, a CustomAdapter can be used to display a list of songs where each item includes the song name, artist, and album art.
In the CustomAdapter class, initialization involves setting up the list of items and the layout resource ID.
When creating a new instance of CustomAdapter, the list of items and the layout resource for each item are passed as parameters.
The getCount() method is overridden to return the total number of items in the list.
If there are 10 items in the list, getCount() should return 10.
The getView() method is crucial for inflating the custom layout for each item in the list.
Within getView(), the data for each item is retrieved and assigned to the appropriate views (e.g., ImageView, TextView) in the layout.
CustomAdapter class in Android is essential for creating customized list views, providing developers with flexibility in designing user interfaces.
import android.os.Bundle; | import android.widget.GridView; | import androidx.appcompat.app.AppCompatActivity; | import java.util.ArrayList; |
onCreate
method is crucial. This method is called when the activity is starting. It performs essential setup tasks for the activity.setContentView(R.layout.activity_main);
line specifies the layout resource for the activity. It inflates the activity UI from the XML layout file.ArrayList
named itemsList
is created to store items. Images are associated with textual descriptions using the items
class.GridView
is initialized with the id grid_view
from the layout.CustomAdapter
) is employed to populate the GridView with data from the items list.Activity Creation
Activities are fundamental components of an Android app.
They represent a single screen with a user interface.
Activities interact to form the complete application.
GridView Implementation
GridView organizes items in a two-dimensional scrolling grid.
It is useful for displaying images or other data in a grid format.
Bundle: Used for passing data between Android components.
GridView: Displays items in a two-dimensional scrolling grid.
AppCompatActivity: Base class for activities supporting AndroidX features.
![]() |
Video Player
00:00
00:11
Use Up/Down Arrow keys to increase or decrease volume.
Are you feeling overwhelmed in the realm of Backend Development? It's time for a positive change! Enroll in our Java Backend Development - Live Course and begin an exciting journey towards efficiently mastering backend development within a set timeframe.
Login
Like