Lesson 49. SimpleAdapter. SetViewText and SetViewImage methods

Lesson 49. SimpleAdapter. SetViewText and SetViewImage methods

In this lesson:

– we use the methods SetViewText and SetViewImage

We already know that SimpleAdapter is able to paste text into TextView elements and images in ImageView. He uses methods for this SetViewText and SetViewImage. We can create your adapter based on SimpleAdapter and implement these methods for our purposes.

These methods provide us View and data, So we can change View depending on the data. As an example, let’s make a list that shows the dynamics of some indicator in terms of days. If the dynamics are positive – we will decorate the elements in green, if negative – in red.

Let’s create a project:

Project name: P0491_SimpleAdapterCustom1
Build Target: Android 2.3.3
Application name: SimpleAdapterCustom1
Package name: ru.startandroid.develop.p0491simpleadaptercustom1
Create Activity: MainActivity

we draw a screen main.xml:


Only the list is on the screen.

And layout for the list item item.xml:


component ivImg will display the down or up arrow, tvValue – the value of the dynamics, tvText – day number.

code MainActivity.java:

package ru.startandroid.develop.p0491simpleadaptercustom1;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class MainActivity extends Activity {

  // имена атрибутов для Map
  final String ATTRIBUTE_NAME_TEXT = "text";
  final String ATTRIBUTE_NAME_VALUE = "value";
  final String ATTRIBUTE_NAME_IMAGE = "image";

  // картинки для отображения динамики 
  final int positive = android.R.drawable.arrow_up_float;
  final int negative = android.R.drawable.arrow_down_float;
  ListView lvSimple;

  /** Called when the activity is first created. */
  public void onCreate(Bundle savedInstanceState) {

    // массив данных
    int[] values = { 8, 4, -3, 2, -5, 0, 3, -6, 1, -1 };

    // упаковываем данные в понятную для адаптера структуру
    ArrayList> data = new ArrayList>(
    Map m;
    int img = 0;
    for (int i = 0; i < values.length; i++) {
      m = new HashMap();
      m.put(ATTRIBUTE_NAME_TEXT, "Day " + (i + 1));
      m.put(ATTRIBUTE_NAME_VALUE, values[i]);
      if (values[i] == 0) img = 0; else
        img = (values[i] > 0) ? positive : negative;
      m.put(ATTRIBUTE_NAME_IMAGE, img);

    // массив имен атрибутов, из которых будут читаться данные
    // массив ID View-компонентов, в которые будут вставлять данные
    int[] to = { R.id.tvText, R.id.tvValue, R.id.ivImg };

    // создаем адаптер
    MySimpleAdapter sAdapter = new MySimpleAdapter(this, data,
        R.layout.item, from, to);

    // определяем список и присваиваем ему адаптер
    lvSimple = (ListView) findViewById(R.id.lvSimple);

  class MySimpleAdapter extends SimpleAdapter {

    public MySimpleAdapter(Context context,
        List> data, int resource,
        String[] from, int[] to) {
      super(context, data, resource, from, to);

    public void setViewText(TextView v, String text) {
      // метод супер-класса, который вставляет текст
      super.setViewText(v, text);
      // если нужный нам TextView, то разрисовываем 
      if (v.getId() == R.id.tvValue) {
        int i = Integer.parseInt(text);
        if (i < 0) v.setTextColor(Color.RED); else
          if (i > 0) v.setTextColor(Color.GREEN);

    public void setViewImage(ImageView v, int value) {
      // метод супер-класса
      super.setViewImage(v, value);
      // разрисовываем ImageView
      if (value == negative) v.setBackgroundColor(Color.RED); else
        if (value == positive) v.setBackgroundColor(Color.GREEN);

The adapter creation code is normal. we come up with data values and pack them into a collection Map-objects. Each Map will consist of three attributes

ATTRIBUTE_NAME_TEXT – text with day number
ATTRIBUTE_NAME_VALUE is the value of the speaker
ATTRIBUTE_NAME_IMAGE – picture id to display, depending on value (positive or negative)

Then we populate the array of mapping data (from) and View (to), create an adapter using our class MySimpleAdapter, And customize the list.

we are looking at implementation MySimpleAdapter. The constructor calls the super-class constructor, here we change nothing. We will change methods:


First, we implement a super-class method that inserts data. And then we look, if View is the TextView that will display the value, then we change the color of the text to red or green depending on the value that it will display.


We implement a super-class method to get ImageView an image, and then change its background depending on the value. The image we are inserting is with an alpha layer, so the background will be visible. ImageView id does not scan because ImageView only has one.

We will save everything and run it.

The picture, value and day were displayed. The background of the picture and the color of the text values ​​change depending on the value – positive or negative.

The example, of course, is not particularly interesting, but it was necessary to consider the work of these methods. Nothing better came to mind)

In the next lesson:

– we use our SimpleAdapter.ViewBinder

Discuss in the forum [45 replies]

Leave a Comment