This lesson:

- using ListView to create a List.

 

Before we begin to study ListView, I suggest to recall the last lesson and the mechanism of the list building, which we used.  We went through an array of data, created a list item within every iteration, filled it with data and added to the list.

The adapter will create list items for us while ListView creating. The adapter needs data and a layout-resource for list item. After passing arguments to the adapter, we assign the adapter to the ListView list. While building, the list requests the items from the adapter, the adapter creates them (using data and layout) and returns them to the list. As a result we see the finished list.

There are different types of lists and adapters. We will study the most simple variant so far.

 

Let’s create a project: 

Project name: P0421_SimpleList
Build Target: Android 2.3.3
Application name: SimpleList
Package name: ru.startandroid.develop.p0421simplelist
Create Activity: MainActivity

Open main.xml and add ListView to the layout (Composite tab):

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello">
    </TextView>
    <ListView
        android:id="@+id/lvMain"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    </ListView>
</LinearLayout>

 

ListView is the list component.

 

Now, we need to create an adapter. Open  MainActivity.java and code: 

 

package ru.startandroid.develop.p0421simplelist;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class MainActivity extends Activity {

  String[] names = { "Иван", "Марья", "Петр", "Антон", "Даша", "Борис",
      "Костя", "Игорь", "Анна", "Денис", "Андрей" };

  /** Called when the activity is first created. */
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    // находим список
    ListView lvMain = (ListView) findViewById(R.id.lvMain);

    // создаем адаптер
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
        android.R.layout.simple_list_item_1, names);

    // присваиваем адаптер списку
    lvMain.setAdapter(adapter);

  }
}

You won’t believe, but this is all code we need for the list creation )

We use array of names as data. Within the onCreate method we determine the list, create an adapter and set it for the list. Let’s find out how we created the adapter.

We used this constructor:  public ArrayAdapter (Context context, int textViewResourceId, T[] objects)

and passed the next parameters to it:
this (context);
android.R.layout.simple_list_item_1 b is a system layout file, which contains the textView.
names is the data array we want to display;

 

We can look at content of  simple_list_item_1. Find Android 2.3.3. in your project, expand it, and expand android.jar

 

Scroll to the bottom and open res.layout.

 

And inside we can find simple_list_item_1, which we use

 

Make a double click on it to see the contents:

<?xml version="1.0" encoding="utf-8"?>
<TextView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/text1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:gravity="center_vertical"
    android:paddingLeft="6dip"
    android:minHeight="?android:attr/listPreferredItemHeight">
</TextView>

This is a simple text view with a set of parameters.

 

When the list asks for the next item while building, the adapter takes this Layout-resource simple_list_item_1, pass it through LayoutInflater and gets the View, converts View to TextView, set its text with data from the data array and returns it to the list.

Let’s save and launch. We can see the list of our data.

 

Using the system layout file simple_list_item_1 is good, because we don’t need to code it by ourselves. But we can create our own resource, in case the system’s resource doesn’t fit us.   

Let’s create layout file  my_list_item.xml in our project’s res/layout folder:

<?xml version="1.0" encoding="utf-8"?>
<TextView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/textView1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center_horizontal"
    android:padding="5dp"
    android:text="TextView"
    android:textColor="#00FF00"
    android:textSize="24sp">
</TextView>

TextView with specified color, text size, alignment and padding

 

Let’s change the code and pass my_list_item layout resource we created to the adapter:

    // создаем адаптер
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
        R.layout.my_list_item, 
        names);

Now the adapter will use it for list items building.

 

Let’s save and launch the app. We will see our list colored with green.

Within the layout resource you may use any View class’ child instead of TextView, it could be Button for example. The main thing is for the object to undergo conversion to TextView. The adapter will specify its text with the setText method and return it to the list.

 

 

A little bit about Context

In one of the previous lessons  I told that Context is used to get access to the basic application functionality. In this lesson we got a good confirmation for these words.

ArrаyAdapter uses LayoutInflater to convert layout-resource into View. But getting LayoutInflater is one of the basic functions and it is unavailable for  ArrаyAdapter class. That’s why we pass a link to Activity as a context into ArrаyAdapter (Activity has an access to the basic functions through the ascending hierarchy of classes). And the ArrayAdapter class uses the context that was passed to it, to get LayoutInflater. It couldn’t do it without the context.

 

The next lesson:

- using the ListView for single and multiple elements selection.


Присоединяйтесь к нам в Telegram:

- в канале StartAndroid публикуются ссылки на новые статьи с сайта startandroid.ru и интересные материалы с хабра, medium.com и т.п.

- в чатах решаем возникающие вопросы и проблемы по различным темам: Android, Kotlin, RxJava, Dagger, Тестирование 

- ну и если просто хочется поговорить с коллегами по разработке, то есть чат Флудильня

- новый чат Performance для обсуждения проблем производительности и для ваших пожеланий по содержанию курса по этой теме 




Language