Android. Customization ListView

ListView, ListAdapter, Android


Customization ListView is common in developing applications for Android OS. ListView (List) allows you to display the same type of information in your application, for example, show the products with prices and features, if you develop applications for online sales. At the same time being in fact a routine operation, however, some questions for novice developers deliver a lot of inconvenience. Some of these inconveniences and questions will be discussed in this article.

Project structure

This lesson is proposed to establish a small list with the flags of countries, called the currencies of these countries, and the abbreviation of the country.

Total is used to create a list of four countries: Russia, South Africa, Singapore, Turkey. Flags of these countries are in the drawable folder. Also there is an xml file to create backgrounds ListViewi flags. For storing names and abbreviations used strings.xml file. Also, a separate xml file to create the ListView layout.

In the Project there are three classes:

  1. MainActivity
  2. MyListAdapter - which is responsible for the transmission of data in the form of a list item
  3. DataFlags - class that is designed to facilitate the transfer of data to the adapter ListView

The formation of layout the ListView

To create a nice looking list in this lesson, the following files:

  1. list_item.xml
  2. flag.xml
  3. listview_selector.xml
  4. styles.xml


This file is a markup directly listview item.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""






This file is created for backgroud ImageView, which will display the flag. The edges of the substrate are rounded to the flag. And also set the color of the substrate.

<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="">

    <solid android:color="@color/blue_grey_100" />


    <corners android:radius="4dp"/>



This marking is used as a background for the ListView. This file is customizable background color of the item in normal mode and when you click on a list item.

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="">
        android:drawable="@color/white" />

        android:drawable="@color/blue_grey_100" />

        android:drawable="@color/blue_grey_100" />



File styles familiar to anyone who has been developing for Android. In this case, it is used only for storing color codes used in this example.


    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">

    <color name="white">#ffffff</color>
    <color name="black">#000000</color>
    <color name="blue_grey_100">#CFD8DC</color>



Layout main Activiti to house our custom ListView

<RelativeLayout xmlns:android=""
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

        android:id="@+id/listViews" />


The main project class -

In this class, is launched basic Activiti project, which will display a custom ListView. Data in ListView transmitted via ArrayList list in which the objects are marked for each data element. The grouping of data for the ListView is produced by a separate class, which forms a data structure in which to store a flag image ID, ID names line the country's currency, as well as the ID string of abbreviations for the currencies.

In fact in this class made standard setting ListView, with the difference that does not use a conventional List, and an ArrayList, which is transferred to an object, and not a single line.

package ru.evileg.listview;

import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;

import java.util.ArrayList;

public class MainActivity extends ActionBarActivity {

    protected void onCreate(Bundle savedInstanceState) {

        // Find the ListView in the markup Activiti
        ListView listView = (ListView) this.findViewById(;

        // Create a ListView, in which the data for the list will be stored
        ArrayList<DataFlags> list = new ArrayList<>();

        /* We fill List data. In this case, the data is transferred to the object that holds the id, 
         * the flags indicating the resource, as well as strings, 
         * which are registered names and abbreviations for the currencies of these currencies 
        list.add(new DataFlags(R.drawable.flag_russian, R.string.russian, R.string.russianRUB));
        list.add(new DataFlags(R.drawable.flag_africa,, R.string.africaZAR));
        list.add(new DataFlags(R.drawable.flag_singapore, R.string.singapore, R.string.singaporeSGD));
        list.add(new DataFlags(R.drawable.flag_turkish, R.string.turkish, R.string.turkishTRY));

        /* Create an adapter that will transfer data from the List item in the ListView and connect it directly to ListView`u
        MyListAdapter myListAdaptery = new MyListAdapter(this, list);

    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(, menu);
        return true;

    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == {
            return true;

        return super.onOptionsItemSelected(item);

All lines which are used for the ListView is stored directly in the resource file strings.xml

    <string name="app_name">ListView</string>
    <string name="action_settings">Settings</string>

    <string name="africaZAR">ZAR</string>
    <string name="russianRUB">RUB</string>
    <string name="singaporeSGD">SGD</string>
    <string name="turkishTRY">TRY</string>

    <string name="africa">South African\nrand</string>
    <string name="russian">Russian\nrouble</string>
    <string name="singapore">Singapore\ndollar</string>
    <string name="turkish">Turkish\nlira</string>

    <string name="flag">flag</string>

This class is used for the formation of the object, in which data is stored for ListView items. Each object serves one of the ListView items in the project. A class is a common variable, and a set of get methods to retrieve data from the object generated by this class.

package ru.evileg.listview;

 * Application ListView
 * Created by EvILeg on 21.07.2015.
public class DataFlags {

    private int flagID;
    private int nameID;
    private int abbreviationID;

    public DataFlags (int _flagID, int _nameID, int _abbreviationID){
        flagID = _flagID;
        nameID = _nameID;
        abbreviationID = _abbreviationID;

    public int getFlagID(){
        return flagID;

    public int getNameID(){
        return nameID;

    public int getAbbreviationID() {
        return abbreviationID;

MyListAdapter class

The most important class in this lesson. It is this class is used to transfer data from ArrayList to the ListView. This class extends the parent class BaseAdapter.

package ru.evileg.listview;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.ArrayList;

 * Application ListView
 * Created by EvILeg on 21.07.2015.
public class MyListAdapter extends BaseAdapter {

     * Create objects for the display appearance element and a list of object that will be work
    private LayoutInflater LInflater;
    private ArrayList<DataFlags> list;

     * The class constructor. In this case, a broadcast data sheet in the adapter list, 
     * which will be direct work
    public MyListAdapter(Context context, ArrayList<DataFlags> data){

        list = data;
        LInflater = (LayoutInflater) context

     * Next come the standard methods of the parent class BaseAdapter. 
     * Please read carefully the differences in the methods and classroom techniques that automatically creates Android Studio. 
     * These methods should be used to work directly with us and ArrayList data structure formed by class DataFlags
    public int getCount() {
        return list.size();

    public DataFlags getItem(int position) {
        return list.get(position);

    public long getItemId(int position) {
        return position;

     * The method in which the appearance of elements is formed with its filling
    public View getView(int position, View convertView, ViewGroup parent) {

        ViewHolder holder;
        View v = convertView;

         * In that case, if the form element is not created, 
         * produced with the help of its creation ViewHolder and tagging of a particular element holder object
        if ( v == null){
            holder = new ViewHolder();
            v = LInflater.inflate(R.layout.list_item, parent, false);
            holder.flag = (ImageView) v.findViewById(;
   = (TextView) v.findViewById(;
            holder.abbreviation = ((TextView) v.findViewById(;

         * Once all elements are defined, the correlation is performed appearance data and the specific position in ListView. 
         * After that, the ArrayList data are collected for the ListView element and transmitted to the exterior element
        holder = (ViewHolder) v.getTag();
        DataFlags dataFlags = getData(position);


        return v;

     * A method that takes an object of the ArrayList to further work with him and transmit its data in a ListView item
    DataFlags getData(int position){
        return (getItem(position));

     * This data structure is needed to ensure that when scrolling through a large list of artifacts and do not arise from skipping data ListView one position to another, 
     * that is achieved by tagging each element ListView
    private static class ViewHolder {
        private ImageView flag;
        private TextView name;
        private TextView abbreviation;

Using ViewHolder crucial because if you do not use this technique, you can get inappropriate behavior ListView, which will occur when uncontrolled data leap from one ListView to another position. And this will occur only in appearance, but in fact the data will remain in their places. There is a mismatch appearance ListView with its contents.


If in the process of learning the lesson did not have any problems and errors, the appearance of the resulting ListView should be similar to the following:

Custom ListView

Custom ListView with pressed element

We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.
- company blog
Support the author Donate

Спасибо за пример. У меня возникает ошибка.

AndroidRuntime: FATAL EXCEPTION: main Подскажите, пожалуйста, с чем это может быть связано?

Честно, вот в этой ошибке может быть что угодно, вплоть до того, что вы просто где-то не в том порядке код запсали.

AndroidRuntime: FATAL EXCEPTION: main

Это просто ошибка в рантайме, для всего, что могло случиться.


Only authorized users can post comments.
Please, Log in or Sign up

Hello, Dear Users of EVILEG!!!

If the site helped you, then support the development of the site financially, please.

You can do it by following ways:

Thank you, Evgenii Legotckoi

April 1, 2020, 8:03 a.m.
Dmitry Kozhinov

C++ - Test 001. The first program and data types

  • Result:40points,
  • Rating points-8
March 30, 2020, 12:47 p.m.

C++ - Test 001. The first program and data types

  • Result:60points,
  • Rating points-1
March 29, 2020, 12:14 p.m.

C++ - Тест 003. Условия и циклы

  • Result:71points,
  • Rating points1
Last comments
March 27, 2020, 2:40 p.m.
Evgenij Legotskoj

Добрый день. В конце пятой статьи скачать можете.
March 27, 2020, 2:28 p.m.
mkdir _

Здравствуйте, а можно, пожалуйста, ссылку на целые исходники, если есть?
March 27, 2020, 4:36 a.m.
Evgenij Legotskoj

Скорее всего также, как и для установки всех остальных переменых в CMake, через использование set
March 27, 2020, 2:47 a.m.
Andrej Jankovich

Ошибка с ярлыками в Windows исправлена в версиии
March 26, 2020, 1:37 p.m.
Andrej Jankovich

но появятся ярлыки, сейчас поправим
Now discuss on the forum
April 2, 2020, 4:53 a.m.
Evgenij Legotskoj

хотя, если вниметльно посмотреть на метод lineNode, то скорее всего проблема в том, что ты создаешь материал в начале метода. Старый скорее всего не удаляется, пока не была удалена нода, а прост…
April 2, 2020, 2:48 a.m.
Evgenij Legotskoj

да нет, правильно код там написан. Может быть дело в том, что чего-то не хватает из dev библиотек, gstreamer тот же самый.
April 2, 2020, 2:46 a.m.
Evgenij Legotskoj

Я думаю, что это где-то описано, но в такой глубине документации и максимум в самых базовых вещах, то есть отдельно в классах этого не пишут, просто потому, что придётся писать для каждого класс…
April 1, 2020, 5:57 p.m.

спасибо за ответ! Попробую больше тестов, поищу зависимости. Если проблема решится, то отпишусь здесь :)
April 1, 2020, 4:37 p.m.

За это отвечает QSvgRender, перед тем как кинуть картинку на виджет её через QSvgRender в QPixMap прогнать надо. Делается это в методе ::render(&) "The QSvgRenderer class is used t…
© EVILEG 2015-2019
Recommend hosting TIMEWEB