You get a bonus - 1 coin for daily activity. Now you have 1 coin

41. Use LayoutInflater to create a list

Lecture



In this lesson:

- make your own version of the list

In the last lesson, we learned why we need the LayoutInflater class and made a small example that looked at the inflate method and its parameters in detail. To fix the topic, let us make another, slightly more complicated example.

We will make your analog list . For a start we will think up the data. Let it again be the staffing table with the names of the workers, positions and disgrace) Ie Each item in our list will contain three non-editable text fields - name , position , salary . And we will place the items in the form of a vertical list.

To implement we need two layout files:
main.xml - main screen for Activity, container for list items
item.xml is a screen with FrameLayout and three text fields in it. This will be a list item.

The application will simultaneously iterate through three data arrays , create for each triples a View element from the item.xml layout file, fill it with data and add it to the vertical LinearLayout in main.xml .

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

Screen 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 provide us with a scrolling list if all items do not fit into the screen. And in it LinearLayout , in which we will add elements.

Item.xml screen:

  <? 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 , and three TextView in it.

Code implementation. 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 much code is needed to make an uncomplicated list. We run a cycle by count of elements in data arrays. In each iteration, we create a View item element from the item-item layout file. In our case, item is a FrameLayout that contains three TextViews . We find them in the created item and fill it with data from arrays.

In the inflate method , we specified root - linLayout to get LayoutParams from it and then use it to adjust the width. Also, for clarity, we color the items with the setBackgroundColor method.

Notice that the third parameter, inflate, is false . Those. we did not immediately add the created View-element to linLayout, but do it at the end of the code using the addView method. There is an explanation. If we specified true, then the method would add item to linLayout and return us linLayout , which is common to all list items. Through linLayout, filling in a TextView with the text we need would be difficult. Therefore, we get item (FrameLayout) item , fill it with TextView data and only then put it to the other items in linLayout using addView method.

All save and run:

  41. Use LayoutInflater to create a list

The list is a success and scrolling works.

The lesson was 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 greatly facilitate the understanding of the list. Because principle is similar. To build a List, we will also need to provide an array of data and a layout file for the items. We will deal with this in the next lesson.

This lesson was coined and written at an altitude of 10 km., In an airplane on the way to Moscow. Through the row, to my left was a guy with a java backpack, printed docks, laptop and something kodil under Android.

Android is everywhere :)

In the next lesson:

- use ListView to build a list

created: 2016-02-08
updated: 2021-03-13
132394



Rating 9 of 10. count vote: 2
Are you satisfied?:


avatar
28.4.2020 8:23

Я не очень поняла следующий момент в уроке.
Мы создали множество объектов View из xml item.xml.
у них есть идентификаторы tvName ,tvPosition и т.д.

И мы потом все эти объекты присоединили к 1 layout - linLayout.
Как такое возможно? Те в этом лайоуте несколько элементов с одинаковыми id?

avatar
28.4.2020 8:24

id уникален, так сказать, в пределах item.xml

avatar
28.4.2020 8:24

есть вопрос про ScrollView
у меня как и написано в уроке в ScrollView лежит LinearLayout в который я загружаю элементы, заданные xml файликами. Работает все хорошо. Но мне нужно организовать прокрутку в конец, т.е. когда добавляешь элемент если он уже не помещается на экран, то прокручивать в конец.
Существует функция scrollTo(x,y), если её повешать на кнопку и нажимать кнопку то он все прокручивает, а если в засунуть в код после добавления элемента в список то не прокручивает..
или еще как-нибудь может быть можно это реализовать?

avatar
28.4.2020 8:24

все разобрался, сделал так
public void scrollDown()
scroll.post(new Runnable()
public void run()
scroll.scrollBy(0, +1500);
//scroll.fullScroll(ScrollView.FOCUS_DOWN);

);


Comments


To leave a comment
If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Mobile Programming (Android IOs)

Terms: Mobile Programming (Android IOs)