Pular para o conteúdo principal

Understanding ArrayAdapter in Android

ArrayAdapter is a class in Android that helps to bind data from a data source to a view in a ListView, Spinner or GridView. It enables developers to display a list of items on the screen in a more efficient way.

In this article, we will explore how to use ArrayAdapter in Android and how to implement it in Kotlin.

Creating an ArrayAdapter

To create an ArrayAdapter, we first need to declare an ArrayList of items that we want to display in the ListView. For instance, let's say we want to display a list of cities. Here's how to declare the ArrayList in Kotlin:

val cities = arrayListOf("New York", "Los Angeles", "Chicago", "Houston", "Philadelphia")

Next, we create an instance of ArrayAdapter and pass in the context, layout resource, and ArrayList as parameters. The layout resource is the layout file for each item in the list. Here's how to create an ArrayAdapter in Kotlin:

val adapter = ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, cities)

The android.R.layout.simple_list_item_1 is a built-in layout resource that displays a single TextView for each item in the list. You can use your own custom layout resource if you want.

Binding the ArrayAdapter to the ListView

To display the list of cities on the screen, we need to bind the ArrayAdapter to the ListView in our layout file. Here's an example of a layout file that contains a ListView:

<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>

In our Kotlin code, we need to get a reference to the ListView and set the ArrayAdapter as its adapter. Here's how to do it:

val listView = findViewById<ListView>(R.id.listView)
listView.adapter = adapter

The adapter variable is the instance of ArrayAdapter that we created earlier.

Customizing the ArrayAdapter

We can customize the ArrayAdapter to display the list of items in a more visually appealing way. For instance, we can use a custom layout resource that displays an image and a text for each item in the list.

Here's an example of a custom layout resource called list_item_layout.xml:

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
>

<ImageView
android:id="@+id/imageView"
android:layout_width="50dp"
android:layout_height="50dp"
android:src="@drawable/city_icon"
/>

<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
/>
</LinearLayout>

In our Kotlin code, we need to create a new instance of ArrayAdapter and pass in the custom layout resource as the layout parameter. Here's how to do it:

val adapter = ArrayAdapter<String>(this, R.layout.list_item_layout, cities)

Now the list of cities will be displayed in a more visually appealing way with an image and a text for each item.

Creating ArrayAdapter From Resource

Not only can arrayadapter be creating using constructors but it can also be created from an external resource.

Android provides a createfromresource() method which is static. This method returns us an ArrayAdapter instance.

Binding Lists and Arrays into an ArrayAdapter

You can bind a list of objects or an array into an ArrayAdapter via the constructor. For array:

ArrayAdapter(Context context, int resource, T[] objects)

For List:

ArrayAdapter(Context context, int resource, List<T> objects)

EXAMPLE:

ArrayAdapter myArrayAdapter = new ArrayAdapter(MainActivity.this,android.R.layout.simple_list_item_1,galaxiesList)

Adding Individual Elements into an ArrayAdapter

Or you can add items individually to an already existing ArrayAdapter or a collection of elements into an existing ArrayAdapter.

To add an object:

myArrayAdapter.add(T object)

This will add the specified object to the end of our arrayadapter.

To add a collection:

myArrayAdapter.addAll(Collection<? extends T> collection)

This will add a Collection to the end of our adapter.

Or add a list that is not necessarily a collection, like say an array:

myArrayAdapter.addAll(T... items)

where T is an Object.

Clearing the ArrayAdapter

This will remove everything from the adapter:

myArrayAdapter.clear()

Getting the total number of items in the ArrayAdapter

We can get the count of items in the arrayadapter using the getCount() method:

int total = myArrayAdapter.getCount();

Getting a particular item from an ArrayAdapter

You can obtain item from an ArrayAdapter:

Object myItem = myArrayAdapter.getItem(position);

You pass the position, an integer.

Getting the Position of a Known Object

Sometimes you don't know the position of an object, but you know the object. So you can get the position by passing the item to the getPosition() method.

int itemPosition = myArrayAdapter.getPosition(item);

ArrayAdapter Examples

1. Android ArrayAdapter - ListView and ArrayList

Android ArrayAdapter - ListView and ArrayList tutorial.

Adapters like ArrayAdapter help bridge the gap between model data and the adapterview,two very different stuff with different responsibilities.Our model data represents our data source.

It maybe from a database or a simple data collection,like say array or arraylist.The adapterview represents the visual representations.They are view children hence are concerned with showing data.

Adapterviews include ListViews,GridViews and spinner. Our adapter shall help link these two. ArrayAdapters work with an array or java.util.List instance.

It takes :

  1. Context.
  2. Resource ID of the view to be used in the adapterview.
  3. List of data to be bound.
What we do :
  • Fill our adapterview with data.
  • Our adapterview in this case is a simple ListView.
  • We use ArrayAdapter as our adapter.
  • Our data source is an arraylist.
  • So we instantiate and set to our listview using the setAdapter() method.
  • While instantiating our adapter we need to pass a context,layout and data source.
  • We handle our itemclicks and show a simple toast message.
What You do :
  • Create a project in android studio.
  • Give it a name and choose minimum and target SDKs.

SECTION 1 : Our Dependencies

Build.Gradle

  • Android Studio has added for us dependencies for AppCompat and Design support libraries.
  • Note we are subclassing AppCompatActivity to make our MainActivity class an activity.
    dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:24.2.0'

}
Our MainActivity

Main Responsibility : LAUNCH OUR APP.

  • It extends AppcompatActivity hence is an activity.
  • Activities are the entry point of android applications.This is no exception.
  • It loads our activity layout.
  • Our activity layout has our ListView.
  • We therefore reference that ListView and set its adapter.
  • We first instantiate our arrayadapter,passing in context,layout and data source.
  • Our arrayadapter is of generic type string.
  • To set our adapter to listview we use the setAdapter() method.
  • Our data source is a simple arraylist.
    package com.tutorials.hp.listviewarraylist;

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.ListView;
import android.widget.Toast;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    ArrayList<String> numbers=new ArrayList<>();
    ListView lv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        lv = (ListView) findViewById(R.id.lv);

        //FILL DATA
        fillData();

        //ADAPTER
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, numbers);
        lv.setAdapter(adapter);

        //LISTENER
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Toast.makeText(MainActivity.this, numbers.get(i), Toast.LENGTH_SHORT).show();
            }
        });
    }

    //FILL DATA
    private void fillData()
    {
        for (int i=0;i<10;i++)
        {
            numbers.add("Number "+String.valueOf(i));
        }
    }
}

SECTION 3 : Our Layouts

ActivityMain.xml Layout.
  • Inflated as our activity's view.
  • Add ListView here.
    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 
    
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.tutorials.hp.listviewarraylist.MainActivity">

    <ListView
        android:id="@+id/lv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
         />
</RelativeLayout>

Conclusion

In this article, we have learned how to use ArrayAdapter in Android to display a list of items on the screen. We have also learned how to customize the ArrayAdapter to display the list in a more visually appealing way. ArrayAdapter is a powerful class in Android that helps to make our apps more efficient and user-friendly.