Освой программирование играючи

Сайт Александра Климова

Шкодим

/* Моя кошка замечательно разбирается в программировании. Стоит мне объяснить проблему ей - и все становится ясно. */
John Robbins, Debugging Applications, Microsoft Press, 2000

Список с использованием HashMap и объектов (SimpleAdapter)

Простой список с пунктами, состоящими из двух текстовых меток. Сами данные берутся из объекта класса Contact.

Создадим разметку для отдельного пункта списка (list_item.xml).


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal" >

    <TextView
        android:id="@+id/text_view_name"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:paddingLeft="10dp"
        android:textSize="25sp" />

    <TextView
        android:id="@+id/text_view_phone"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:paddingRight="10dp"
        android:textSize="25sp" />

</LinearLayout>

Создадим отдельный класс ContactMap на основе HashMap:


package ru.alexanderklimov.listview;

import java.util.HashMap;

public class ContactMap extends HashMap<String, String> {

    static final String NAME = "name";
    static final String PHONE = "phone";

    // Конструктор с параметрами
    public ContactMap(String name, String phone) {
        super();
        super.put(NAME, name);
        super.put(PHONE, phone);
    }
}

Выводим данные в список.


package ru.alexanderklimov.listview;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

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

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

        ArrayList<ContactMap> list = new ArrayList<>();
        // Заполняем данными
        list.add(new ContactMap("Барсик", "1111"));
        list.add(new ContactMap("Мурзик", "22222"));
        list.add(new ContactMap("Рыжик", "33333"));
        list.add(new ContactMap("Кузя", "44444"));
        list.add(new ContactMap("Пушок", "55555"));
        list.add(new ContactMap("Васька", "64656"));

        ListAdapter adapter = new SimpleAdapter(this, list, R.layout.list_item,
                new String[] { ContactMap.NAME, ContactMap.PHONE }, new int[] {
                R.id.text_view_name, R.id.text_view_phone });
        listView.setAdapter(adapter);
    }
}

HashMap, объект, SimpleAdapter

Три колонки

Переделаем пример, чтобы список отражал три колонки вместо двух. Изменим разметку для элемента списка, добавив ещё одну текстовую метку.


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal" >

    <TextView
        android:id="@+id/text_view_id"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:paddingStart="10dp"
        android:textSize="25sp" />

    <TextView
        android:id="@+id/text_view_name"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="2"
        android:paddingStart="10dp"
        android:textSize="25sp" />

    <TextView
        android:id="@+id/text_view_phone"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:paddingEnd="10dp"
        android:textSize="25sp" />

</LinearLayout>

Также нужно изменить класс ContactMap из предыдущего примера, добавив новое поле - идентификатор кота. Для экономии места обойдёмся без класса и вставим данные сразу в адаптер.


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

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

    ArrayList<HashMap<String, String>> arrayList = new ArrayList<>();
    HashMap<String, String> hashMap;

    hashMap = new HashMap<>();
    hashMap.put("ID", "1");
    hashMap.put("Name", "Барсик");
    hashMap.put("Phone", "1111");
    arrayList.add(hashMap);

    hashMap = new HashMap<>();
    hashMap.put("ID", "2");
    hashMap.put("Name", "Мурзик");
    hashMap.put("Phone", "22222");
    arrayList.add(hashMap);

    hashMap = new HashMap<>();
    hashMap.put("ID", "3");
    hashMap.put("Name", "Рыжик");
    hashMap.put("Phone", "33333");
    arrayList.add(hashMap);

    hashMap = new HashMap<>();
    hashMap.put("ID", "4");
    hashMap.put("Name", "Кузя");
    hashMap.put("Phone", "44444");
    arrayList.add(hashMap);

    hashMap = new HashMap<>();
    hashMap.put("ID", "5");
    hashMap.put("Name", "Пушок");
    hashMap.put("Phone", "55555");
    arrayList.add(hashMap);

    hashMap = new HashMap<>();
    hashMap.put("ID", "6");
    hashMap.put("Name", "Васька");
    hashMap.put("Phone", "64656");
    arrayList.add(hashMap);

    ListAdapter adapter = new SimpleAdapter(this, arrayList, R.layout.list_item,
            new String[]{"ID", "Name", "Phone"},
            new int[]{
            R.id.text_view_id, R.id.text_view_name, R.id.text_view_phone});
    listView.setAdapter(adapter);
}

HashMap, объект, SimpleAdapter

Дополнительное чтение

SimpleAdapter

Реклама