Lesson 50. SimpleAdapter. we use ViewBinder

In this lesson:

– we use our SimpleAdapter.ViewBinder

adapter SimpleAdapter in his work compares Viewcomponents and values ​​of Map-objects. We’ve covered the previous tutorials on how it does the default and what View components can work with. But if we lack these opportunities, we always can create your own handler and assign it to the adapter.

This uses the setViewBinder (SimpleAdapter.ViewBinder viewBinder) method, which requires a SimpleAdapter.ViewBinder object to enter. We create our own version of this binder and implement the setViewValue method (View view, Object data, String textRepresentation), in which we prescribe all the logic of data and component matching (Binging). The method returns a boolean value.

The algorithm of the adapter is this: it first checks whether it was given a third party binder.

If it finds, then it executes its method setViewValue. If the method returns trueThe adapter then considers the processing successful completed, if false – then he performs Binding in his standard the algorithm we covered in the previous lessons.

if the adapter does not find a third-party binder, he also performs standard Binding.

That is, our task is to complete the method SimpleAdapter.ViewBinder.setViewValue. And now there are no restrictions on TextView or ImageView, any component can be processed and filled. Let’s create an example in which to fill in the value ProgressBar and change the color LinearLayout.

It will be a monitoring application that reflects the capacity utilization of a system in a few days. ProgressBar will show the download level and the entire list item will be colored in color depending on the download level.

Let’s create a project:

Project name: P0501_SimpleAdapterCustom2
Build Target: Android 2.3.3
Application name: SimpleAdapterCustom2
Package name: ru.startandroid.develop.p0501simpleadaptercustom2
Create Activity: MainActivity

we draw a screen main.xml:


List only.

We will need to create the res / values ​​/ filecolors.xml, Where we list the colors we need:


Now we create a layout for the list items res / layout /item.xml:


llLoad – LinearLayout that occupies the entire list item and which we will decorate,
tvLoad – text-info,
pbLoad – download indicator.

code MainActivity.java:

package ru.startandroid.develop.p0501simpleadaptercustom2;

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

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SimpleAdapter;

public class MainActivity extends Activity {

  // имена атрибутов для Map
  final String ATTRIBUTE_NAME_TEXT = "text";
  final String ATTRIBUTE_NAME_PB = "pb";
  final String ATTRIBUTE_NAME_LL = "ll";

  ListView lvSimple;

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

    // массив данных
    int load[] = { 41, 48, 22, 35, 30, 67, 51, 88 };

    // упаковываем данные в понятную для адаптера структуру
    ArrayList> data = new ArrayList>(
    Map m;
    for (int i = 0; i < load.length; i++) {
      m = new HashMap();
      m.put(ATTRIBUTE_NAME_TEXT, "Day " + (i+1) + ". Load: " + load[i] + "%");
      m.put(ATTRIBUTE_NAME_PB, load[i]);
      m.put(ATTRIBUTE_NAME_LL, load[i]);

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

    // создаем адаптер
    SimpleAdapter sAdapter = new SimpleAdapter(this, data, R.layout.item,
        from, to);
    // Указываем адаптеру свой биндер
    sAdapter.setViewBinder(new MyViewBinder());

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

  class MyViewBinder implements SimpleAdapter.ViewBinder {
    int red = getResources().getColor(R.color.Red);
    int orange = getResources().getColor(R.color.Orange);
    int green = getResources().getColor(R.color.Green);
    public boolean setViewValue(View view, Object data,
        String textRepresentation) {
      int i = 0;
      switch (view.getId()) {
      // LinearLayout
      case R.id.llLoad:
        i = ((Integer) data).intValue();
        if (i < 40) view.setBackgroundColor(green); else 
          if (i < 70) view.setBackgroundColor(orange); else
        return true;
      // ProgressBar  
      case R.id.pbLoad:
        i = ((Integer) data).intValue();
        return true;
      return false;

We look at the code. We fill the load data set on a 100-point scale. Form the data for the adapter: in TextView we will provide short information (String), And c ProgressBar and LinearLayout - download value (int). We populate the mapping arrays, create an adapter, tell it to use our binder, and customize the list.

nested class MyViewBinder is our implementation of the binder. We need to implement the method setViewValueThe adapter that will be used to map data from Map and View components. At the entrance he goes:

view - View component
given - data for him
textRepresentation - text representation (data.toString () or empty String, but never null)

So, we're looking at implementation. We first check which component we were given for processing.

In the case of llLoad we are expecting data of type int, so we bring Object to Integer and get the load data from the array. And then we look at the level of this download. If less than 40, then we will assume that everything is ok, the background color is green. From 40 to 70 - attention, color yellow. Above 70 - high load, red. we return true. It is important! Thus we tell the adapter that we are successful fulfilled You do not need to bind for this component and perform standard processing for it.

In the case of pbLoad we also expect int and perform casting. And then just call the setProgress method and pass it the values. At the end we return true - we have successfully processed the component, standard processing is not required.

For all other View-Components method setViewValue will return false. This means the components will go on standard processing by the adapter. In our case, this is the way to go tvLoad and the adapter itself will pass it the text from Map, our intervention is not required.

We save and run everything.

Here is a picture. LinearLayout was full of color, ProgressBar displayed loading level, TextView showed information about loading day and time.

In the next lesson:

- we use SimpleAdapter to build the list
- add and delete entries in the list

Discuss in the forum [75 replies]

Leave a Comment