2011年10月14日星期五

讀取多選項列表視圖(Read multiple choice ListView)

讀取多選項列表視圖(Read multiple choice ListView)

package com.MultiChoiceList;

import android.app.Activity;
import android.os.Bundle;
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;
import android.widget.TextView;

public class MultiChoiceList extends Activity {

ListView list;
TextView selection;

String[] options = {"Option 1", "Option 2", "Option 3",
"Option 4", "Option 5", "Option 6"};

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
list = (ListView)findViewById(R.id.list);
selection = (TextView)findViewById(R.id.selection);

ArrayAdapter<String> adapter
= new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_multiple_choice,
options);
list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

list.setAdapter(adapter);

list.setOnItemClickListener(new OnItemClickListener(){

@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
selection.setText(ReadSelection());
}});
}

String ReadSelection(){

String selected = "";
int cntChoice = list.getCount();
SparseBooleanArray sparseBooleanArray = list.getCheckedItemPositions();

for(int i = 0; i < cntChoice; i++){
if(sparseBooleanArray.get(i)) {
selected += list.getItemAtPosition(i).toString() + "\n";
}
}

return selected;
}
}


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<TextView
android:id="@+id/selection"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<ListView
android:id="@+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</LinearLayout>




沒有留言:

發佈留言