Friday, November 27, 2009

ListView and ListActivity Demo

This is a slightly modified version at apiDemo. It demonstrates how you select multiple items on a ListView and display the results on a TextView.

main.xml layout (Note that the ListView has “choiceMode” set as “multipleChoice” and that the ListView has an id of “@android:id/list”):




android:orientation=”vertical”

android:layout_width=”fill_parent”

android:layout_height=”fill_parent”

>


android:layout_width=”fill_parent”

android:layout_height=”wrap_content”

android:text=” “

android:id=”@+id/selection”

/>


android:id=”@android:id/list”

android:choiceMode=”multipleChoice”

android:layout_width=”fill_parent”

android:layout_height=”wrap_content”/>

Main java class:

package com.mh.android.test;

import android.app.ListActivity;

import android.os.Bundle;

import android.util.SparseBooleanArray;

import android.view.View;

import android.widget.ArrayAdapter;

import android.widget.ListView;

import android.widget.TextView;

public class ListAdapterTest extends ListActivity {

String[] items= {“lorem”, “ipsum”, “dolor”, “sit”, “amet”,

“consectetuer”, “adipiscing”, “elit”, “morbi”, “vel”,

“ligula”, “vitae”, “arcu”, “aliquet”, “mollis”,

“etiam”, “vel”, “erat”, “placerat”, “ante”,

“porttitor”, “sodales”, “pellentesque”, “augue”, “purus”};

TextView selection;

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

setListAdapter(new ArrayAdapter(this,

android.R.layout.simple_list_item_multiple_choice,

items));

selection = (TextView) findViewById(R.id.selection);

}

@Override

protected void onListItemClick(ListView parent, View v, int position, long id) {

// Clear the TextView before we assign the new content.

selection.setText(” “);

// get array of booleans for which positions are selected in the items.

SparseBooleanArray chosen = parent.getCheckedItemPositions();

for(int i=0; i
// if the item is selected by the user, we display it on the TextView.

if(chosen.get(i)) {

selection.append(items[i]+” “);

}

}

}

}

[Via http://maohao.wordpress.com]

No comments:

Post a Comment