Lesson 43. Single and Multiple Choices in ListView

Lesson 43. Single and Multiple Choices in ListView


In this lesson:

– we use ListView for single and multiple element selection

There is a need to allow the user to select one or more items from the list. Let’s see how this can be implemented.

Let’s create a project:

Project name: P0431_SimpleListChoice
Build Target: Android 2.3.3
Application name: SimpleListChoice
Package name: ru.startandroid.develop.p0431simplelistchoice
Create Activity: MainActivity

we draw a screen main.xml:



    
    
    

list lvMain and button btnChecked, After clicking on which we will list the items marked in the list.

I suggest that we have resource files and we can use them. We will find a resource file in our project res / values ​​/ strings.xml and add an array of names. As a result, I got a file with the following content:



    Hello World, MainActivity!
    SimpleListChoice
    
        Иван
        Марья
        Петр
        Антон
        Даша
        Борис
        Костя
        Игорь
        Анна
        Денис
        Вадим
        Ольга
        Сергей
    

We will get an array of names from this list. This is more convenient and correct than listing all elements of an array in java code.

Kodyma MainActivity.java:

package ru.startandroid.develop.p0431simplelistchoice;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;

public class MainActivity extends Activity implements OnClickListener {

  final String LOG_TAG = "myLogs";

  ListView lvMain;
  String[] names;

  /** Called when the activity is first created. */
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    lvMain = (ListView) findViewById(R.id.lvMain);
    // устанавливаем режим выбора пунктов списка 
    lvMain.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
    // Создаем адаптер, используя массив из файла ресурсов
    ArrayAdapter adapter = ArrayAdapter.createFromResource(
        this, R.array.names,
        android.R.layout.simple_list_item_single_choice);
    lvMain.setAdapter(adapter);

    Button btnChecked = (Button) findViewById(R.id.btnChecked);
    btnChecked.setOnClickListener(this);

    // получаем массив из файла ресурсов
    names = getResources().getStringArray(R.array.names);
  }

  public void onClick(View arg0) {
    // пишем в лог выделенный элемент
    Log.d(LOG_TAG, "checked: " + names[lvMain.getCheckedItemPosition()]);
  }
}

We set the list to select mode – CHOICE_MODE_SINGLE. This means that the list will be saved position the latter pressed item and we can always request this information from him. Next we create adapter, But not through the usual constructor, but using the createFromResource method. The input parameters are almost the same as in the usual constructor, but instead of an array of data, we specify array of rows in resourcesWhich we created a little earlier. As the layout resource for the items we use the system simple_list_item_single_choice. It is just sharpened for such use.

Next we find the button btnChecked and give it to her Activity as handler. And in the end we read ours an array of names with resource file into an array of rows.

IN handler we press the button we display in log name from the array. We use the position of an item in the list as an index. The sequence of elements in the array and in the list are the same.

We all save, run and see the list. Highlight any thread item:

press the button Get checked items and look at the log:

checked: Dasha

Everything is correct.

Now let’s change the program code a bit and get a multiple choice list.

    // устанавливаем режим выбора пунктов списка 
    lvMain.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
    // Создаем адаптер, используя массив из файла ресурсов
    ArrayAdapter adapter = ArrayAdapter.createFromResource(
        this, R.array.names,
        android.R.layout.simple_list_item_multiple_choice);

we replaced CHOICE_MODE_SINGLE on CHOICE_MODE_MULTIPLE and now the list will store the positions of the selected items. Also we replaced simple_list_item_single_choice on simple_list_item_multiple_choice – the list items will now allow multiple selection.

method onClick rewrite as follows:

  public void onClick(View arg0) {
    // пишем в лог выделенные элементы
    Log.d(LOG_TAG, "checked: ");
    SparseBooleanArray sbArray = lvMain.getCheckedItemPositions();
    for (int i = 0; i < sbArray.size(); i++) {
      int key = sbArray.keyAt(i);
      if (sbArray.get(key))
        Log.d(LOG_TAG, names[key]);
    }
  }

We get the positions of the selected items as a SparseBooleanArray object. He is Map (int, boolean). key (Int) is the position of the element, and value (Boolean) is a highlighted list item or not. moreover SparseBooleanArray saves the info not about everyone points, but only about those with whom they spent action (Allocated and unselected). We sort through its contents, get it position item and if item highlighted, Then output to the log name from the array corresponding to the position of the item.

We save everything, launch the application. There are several elements:

press the button Get checked items and look at the log:

checked:
Mary
Anton
Kostya

What we have selected, then returned the list to us.

As you can see, the difference between a regular list and a list with the possibility of selecting items is only in different modes ChoiceMode and in using different layout resources for list items.

By the way, here we see again why it is necessary Context when creating adapter. Without it, the adapter would not be able to reach file resources. method getResources from the adapter no, And it uses the specified contextWhich contains such a method.

In the next lesson:

- ListView Events: Clicking - onItemClick, Selecting - onItemSelect, Scrolling - onScroll




Discuss in the forum [83 replies]

Leave a Comment