This lesson:

- making a list option.

 

The last lesson we found out usage of the LayoutInflater class and made a little example, within which we  studied in detail the inflate method and its parameters. To consolidate our skills, we will make a more complex example.

We will make a list analogue. At first, we should come up with the data. Let it one more time be a staffing table with employees’ names, positions and salary. I.e. an every list item will contain tree TextViews - name, position, salary.  We will place the items in a form of a vertical list.

We will need two layout files for implementation:
main.xml is a MainActivity layout, we will use it as a container for the list items
item.xml is a list item layout.

The application will parse three data arrays in parallel, create a view from item.xml for each array item, fill it with data and add a vertical LinearLayout into main.xml.

 

Let’s create a project:

 

Project name: P0411_LayoutInflaterList
Build Target: Android 2.3.3
Application name: LayoutInflaterList
Package name: ru.startandroid.develop.p0411layoutinflaterlist
Create Activity: MainActivity

 

main.xml:

<?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="wrap_content"
        android:layout_height="wrap_content"
        android:text="Staff list"
        android:layout_gravity="center_horizontal">
    </TextView>
    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/scroll">
        <LinearLayout
            android:id="@+id/linLayout"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">
        </LinearLayout>
    </ScrollView>
</LinearLayout>

ScrollView will let us scroll the list in case it won’t fit the screen. We will add items into LinearLayout.

item.xml

 

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:layout_marginTop="10dp">
    <TextView
        android:id="@+id/tvName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView"
        android:layout_gravity="top|center_horizontal"
        android:textSize="24sp">
    </TextView>
    <TextView
        android:id="@+id/tvPosition"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView"
        android:layout_gravity="bottom|left"
        android:layout_marginLeft="5dp">
    </TextView>
    <TextView
        android:id="@+id/tvSalary"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView"
        android:layout_gravity="bottom|right"
        android:layout_marginRight="5dp">
    </TextView>
</FrameLayout> 

FrameLayout with three TextViews in it.

 

Let’s code MainActivity.java:

package ru.startandroid.develop.p0411layoutinflaterlist;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;
import android.widget.TextView;

public class MainActivity extends Activity {

  String[] name = { "Иван", "Марья", "Петр", "Антон", "Даша", "Борис",
      "Костя", "Игорь" };
  String[] position = { "Программер", "Бухгалтер", "Программер",
      "Программер", "Бухгалтер", "Директор", "Программер", "Охранник" };
  int salary[] = { 13000, 10000, 13000, 13000, 10000, 15000, 13000, 8000 };

  int[] colors = new int[2];

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

    colors[0] = Color.parseColor("#559966CC");
    colors[1] = Color.parseColor("#55336699");

    LinearLayout linLayout = (LinearLayout) findViewById(R.id.linLayout);

    LayoutInflater ltInflater = getLayoutInflater();

    for (int i = 0; i < name.length; i++) {
      Log.d("myLogs", "i = " + i);
      View item = ltInflater.inflate(R.layout.item, linLayout, false);
      TextView tvName = (TextView) item.findViewById(R.id.tvName);
      tvName.setText(name[i]);
      TextView tvPosition = (TextView) item.findViewById(R.id.tvPosition);
      tvPosition.setText("Должность: " + position[i]);
      TextView tvSalary = (TextView) item.findViewById(R.id.tvSalary);
      tvSalary.setText("Оклад: " + String.valueOf(salary[i]));
      item.getLayoutParams().width = LayoutParams.MATCH_PARENT;
      item.setBackgroundColor(colors[i % 2]);
      linLayout.addView(item);
    }
  }
} 

Not so much code, to make a simple list. We start the loop by the number of elements in the data arrays. We create a view item from  item.xml within every iteration. In our case item is a FrameLayout, which contains three TextViews. We find them in item we have created, and fill in with data from the arrays. 

We specified root as a linLayout for the inflate method, to get LayoutParams from it and further use it for the width adjustment.  Also, for clarity, we color the items with the setBackgroundColor method.

Note, that we specified the third parameter inflate as false. I.e. we did not immediately add the generated View-element to linLayout, but we did it at the end of the code with the addView method.This has an explanation. In case we specified true, the method would add item to the linLayout and return a linLayout, common for all list items. It would be difficult to fill TextView with data we need through the linLayout. So, we get an item, fill its TextView with data, and only then put it to the other items in linLayout with the addView method.

 

Let’s save and launch: 

The list is displayed, the scrolling works. 

 

The lesson turned out short but useful.  Just in case, I want to note that this is not yet a classic Android-list called List. But this example will make the understanding of the list creation much easier, because the principle is similar.  We will similarly provide data array and item layout for list creation. We will do this in the next lesson.

 

The next lesson:

- building a list using ListView;

 


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

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

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

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

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




Language