Android listview множественный выбор

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

SparseBooleanArray selectedItems = lv.getCheckedItemPositions();          
int id1 = lv.getCheckedItemPosition();        
Toast.makeText(getApplicationContext(), "" + id1, Toast.LENGTH_SHORT).show();

for (int i = 0; i < lv_arr.length; i++) {
    if (selectedItems.get(i)) {
        String[] getstring = (String) lv.getAdapter().getItem(
            selectedItems.keyAt(i));
        System.out.println(""+getstring));
    }
}

3 ответа

Решение

Привет, я использовал String для сохранения всех отмеченных пунктов из списка. Посмотрите код ниже:

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;



public class ViewsActivity extends Activity 
{

    private ListView lView;
    private String lv_items[] = { "Android", "iPhone", "BlackBerry",
            "AndroidPeople", "J2ME", "Listview", "ArrayAdapter", "ListItem",
            "Us", "UK", "India" };
    private String my_sel_items;

    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.main);
        my_sel_items=new String();

        lView = (ListView) findViewById(R.id.ListView01);

        lView.setAdapter(new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_multiple_choice, lv_items));
        lView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

        lView.setOnItemClickListener(new OnItemClickListener() {

            public void onItemClick(AdapterView arg0, View arg1, int arg2,long arg3)
            {
                //List list = new ArrayList();
                my_sel_items=new String("Selected Items");
                SparseBooleanArray a = lView.getCheckedItemPositions();

                for(int i = 0; i < lv_items.length ; i++)
                {
                    if (a.valueAt(i))
                    {
                     /*
                        Long val = lView.getAdapter().getItemId(a.keyAt(i));
                        Log.v("MyData", "index=" + val.toString()
                             + "item value="+lView.getAdapter().getItem(i));
                        list.add(lView.getAdapter().getItemId((a.keyAt(i))));
                     */

                        my_sel_items = my_sel_items + "," 
                            + (String) lView.getAdapter().getItem(i);
                    }
                }
                Log.v("values",my_sel_items);
            }
        });
    }
}

В фрагменте кода @Kartik я получаю Index Out Of Bound Exception на этой линии:

if (a.valueAt (i))

и некоторые пошаговые индексы.

Я нашел этот пример, он делает именно то, что вы хотите.

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    mSelectedItems = new ArrayList();  // Where we track the selected items
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    // Set the dialog title
    builder.setTitle(R.string.pick_toppings)
    // Specify the list array, the items to be selected by default (null for none),
    // and the listener through which to receive callbacks when items are selected
           .setMultiChoiceItems(R.array.toppings, null,
                      new DialogInterface.OnMultiChoiceClickListener() {
               @Override
               public void onClick(DialogInterface dialog, int which,
                       boolean isChecked) {
                   if (isChecked) {
                       // If the user checked the item, add it to the selected it@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    mSelectedItems = new ArrayList();  // Where we track the selected items
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    // Set the dialog title
    builder.setTitle(R.string.pick_toppings)
    // Specify the list array, the items to be selected by default (null for none),
    // and the listener through which to receive callbacks when items are selected
           .setMultiChoiceItems(R.array.toppings, null,
                      new DialogInterface.OnMultiChoiceClickListener() {
               @Override
               public void onClick(DialogInterface dialog, int which,
                       boolean isChecked) {
                   if (isChecked) {
                       // If the user checked the item, add it to the selected ems
                       mSelectedItems.add(which);
                   } else if (mSelectedItems.contains(which)) {
                       // Else, if the item is already in the array, remove it 
                       mSelectedItems.remove(Integer.valueOf(which));
                   }
               }
           })
    // Set the action buttons
           .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
               @Override
               public void onClick(DialogInterface dialog, int id) {
                   // User clicked OK, so save the mSelectedItems results somewhere
                   // or return them to the component that opened the dialog
                   ...
               }
           })
           .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
               @Override
               public void onClick(DialogInterface dialog, int id) {
                   ...
               }
           });

    return builder.create();
}
Другие вопросы по тегам