Below is a simple yet effective solution of using checkbox in listviews.
XML File
<?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" />
<ListView android:id="@+id/list_view" android:layout_width="fill_parent"
android:layout_height="wrap_content"></ListView>
<Button android:id="@+id/show_btn" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="Show Selected Items" />
</LinearLayout>
Java source code
public class TryMultipleChoiceListViewActivity extends Activity {
private ListView lv;
private String[] s;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
lv=(ListView) findViewById(R.id.list_view);
Button btn=(Button) findViewById(R.id.show_btn);
s=new String[]{"China","USA","Canada","South Africa"};
lv.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_multiple_choice,s));
lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
SparseBooleanArray id=lv.getCheckedItemPositions();
StringBuffer sb=new StringBuffer();
for(int i=0;i<lv.getCount();i++)
{
if(id.get(i)){
sb.append(s[i]+" ");
}
}
sb.append("are chosen!");
Toast.makeText(TryAndroidProgressDialogActivity.this, sb.toString(), Toast.LENGTH_SHORT).show();
}
});
}
}
Hope this can help some people who are new to Android!