차근차근/Android
listview + checkbox
ANDROID: MULTIPLE SELECTION LISTVIEW
http://theopentutorials.com/tutorials/android/listview/android-multiple-selection-listview/
Contents [hide]
Project Description
- In the previous Android ListView examples, we created ListView with single selection mode.
- In this example, we will create a ListView with multiple selection mode with button click event. On button click event, we retrieve the selected list view items and create a Bundle with array of selected items and store it in Intent and start another activity (ResultActivity).
- ResultActivity retrieves the array and displays the result in ListView.
Environment Used
- JDK 6 (Java SE 6)
- Eclipse Indigo IDE for Java EE Developers (3.7.1)
- Android SDK 4.0.3 / 4.1 Jelly Bean
- Android Development Tools (ADT) Plugin for Eclipse (ADT version 20.0.0)
- Refer this link to setup the Android development environment
Prerequisites
Create Android Project
- Create a new Android Project and name it as “ListViewMultipleSelection“.
- Enter the package name as “com.theopentutorials.android“.
- Enter the Activity name as “ListViewMultipleSelectionActivity“.
- Click Finish.
strings.xml
Open res/values/string.xml and replace it with following content.
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="hello">Hello World, ListViewMultipleSelectionActivity!</string> <string name="app_name">ListViewMultipleSelection</string> <string name="result_activity">ResultActivity</string> <string name="submit">Submit</string> <string-array name="sports_array"> <item>Shuttle Badminton</item> <item>Tennis</item> <item>Table Tennis</item> <item>Basket Ball</item> <item>Foot Ball</item> <item>Volley Ball</item> <item>Hockey</item> <item>Swimming</item> </string-array> </resources>
XML layout files
This application uses two layout files,
res/layout/main.xml | Represents first screen used by ListViewMultipleSelectionActivity.java |
res/layout/result.xml | Represents second screen used by ResultActivity.java |
main.xml
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" > <Button android:id="@+id/testbutton" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:text="@string/submit" /> <ListView android:id="@+id/list" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_above="@id/testbutton" android:layout_alignParentTop="true" /> </RelativeLayout>
result.xml
<?xml version="1.0" encoding="utf-8"?> <ListView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/outputList" android:layout_width="fill_parent" android:layout_height="fill_parent" />
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.theopentutorials.android" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="15" /> <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" > <activity android:name=".ListViewMultipleSelectionActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".ResultActivity" android:label="@string/result_activity" > </activity> </application> </manifest>
Activity classes
ListViewMultipleSelectionActivity.java
package com.theopentutorials.android; import java.util.ArrayList; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.util.SparseBooleanArray; import android.view.View; import android.view.View.OnClickListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; public class ListViewMultipleSelectionActivity extends Activity implements OnClickListener { Button button; ListView listView; ArrayAdapter<String> adapter; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); findViewsById(); String[] sports = getResources().getStringArray(R.array.sports_array); adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice, sports); listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); listView.setAdapter(adapter); button.setOnClickListener(this); } private void findViewsById() { listView = (ListView) findViewById(R.id.list); button = (Button) findViewById(R.id.testbutton); } public void onClick(View v) { SparseBooleanArray checked = listView.getCheckedItemPositions(); ArrayList<String> selectedItems = new ArrayList<String>(); for (int i = 0; i < checked.size(); i++) { // Item position in adapter int position = checked.keyAt(i); // Add sport if it is checked i.e.) == TRUE! if (checked.valueAt(i)) selectedItems.add(adapter.getItem(position)); } String[] outputStrArr = new String[selectedItems.size()]; for (int i = 0; i < selectedItems.size(); i++) { outputStrArr[i] = selectedItems.get(i); } Intent intent = new Intent(getApplicationContext(), ResultActivity.class); // Create a bundle object Bundle b = new Bundle(); b.putStringArray("selectedItems", outputStrArr); // Add the bundle to the intent. intent.putExtras(b); // start the ResultActivity startActivity(intent); } }
- To load the list view items, we first get the string array resource and used it in ArrayAdapter. We use the list view row layout provided by the Android system (android.R.layout.simple_list_item_multiple_choice) and setting the selection mode as multiple using ListView.CHOICE_MODE_MULTIPLE.
- We invoke getCheckedItemPositions() on list view object which returns the set of checked items (as SparseBooleanArray) in the list
ResultActivity.java
package com.theopentutorials.android; import android.app.Activity; import android.os.Bundle; import android.widget.ArrayAdapter; import android.widget.ListView; public class ResultActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.result); Bundle b = getIntent().getExtras(); String[] resultArr = b.getStringArray("selectedItems"); ListView lv = (ListView) findViewById(R.id.outputList); ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, resultArr); lv.setAdapter(adapter); } }
Output
Run your application
First Screen
Project Folder Structure
The complete folder structure of this example is shown below.
2.BaseAdapter+ListView+CheckBox:
http://schimpf.es/listview-with-checkboxes-inside/ < -안들어가짐
3.使用ViewBinder添加CheckBox:
http://hi.baidu.com/xghhy/item/391caf9db4c36cdc1e427179
摘要: Android Email app 来举个例子,这种app需要的基本功能中有 1. 从服务器接收的Email数据保存在本地数据库里面(SQLite) 2. Email数据中除了内容以外还会有一个boolean 变量(也可以用int 0/1 代替)来标记“已读”“未读”。
简单来说从SQLite里面读取已读变量,让系统在app中的List上画一个Checkbox。(根据SQLite里面的数据)
1. 首先定义一个 SimpleCursorAdapter.ViewBinder
SimpleCursorAdapter.ViewBinder viewBinder = new SimpleCursorAdapter.ViewBinder() {
@Override
public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
if(view instanceof CheckBox) {
CheckBox checkbox = (CheckBox)view;
int value = cursor.getInt(columnIndex);
if(value==1) {
checkbox.setChecked(true);
return true;
}
else if(value==0) {
checkbox.setChecked(false);
return true;
}
else
return false;
}
return false;
}
};
注:Cursor的可以有好几个行,这里的columnIndex表示一个行的索引。
2. 下面定义一个SimpleCursorAdapter本身 然后利用 SimpleCursorAdapter.setViewBinder()来套用之前定义的ViewBinder。
SimpleCursorAdapter simpleCursorAdapter = new SimpleCursorAdapter(this, R.layout.list_item,
notificationCursor, new String[] { "subject", "content", "date", "unread"},
new int[] {R.id.subject, R.id.content, R.id.date, R.id.unread});
simpleCursorAdapter.setViewBinder(viewBinder);
注:这里的R.id.unread是指布局xml文件的里的CheckBox部件。 R.id.subject, R.id.content, R.id.date是其他Email数据。
ListAdapter adapter = simpleCursorAdapter;
setListAdapter(adapter); // Activity 是 ListActivity
3. 这样就完事了,下面的二行是ListAdapter的老规矩,简单吧。
3.ListView+SimpleCursorAdapter+checkbox:
【android】ListView+SimpleCursorAdapter+checkbox实现批量删除
http://blog.csdn.net/chdjj/article/details/16356797
最近项目有个需求。
- public class CheckBoxAdapter4TextNote extends SimpleCursorAdapter
- {
- private ArrayList<Integer> selection = new ArrayList<Integer>();//记录被选中条目id
- private int mCheckBoxId = 0;//listView条目的样式对应的xml资源文件名(必须包含checkbox)
- private String mIdColumn;//数据库表的id名称
- public CheckBoxAdapter4TextNote(Context context, int layout, Cursor c,
- String[] from, int[] to, int checkBoxId, String idColumn,
- int flags)
- {
- super(context, layout, c, from, to, flags);
- mCheckBoxId = checkBoxId;
- mIdColumn = idColumn;
- }
- @Override
- public int getCount()
- {
- return super.getCount();
- }
- @Override
- public Object getItem(int position)
- {
- return super.getItem(position);
- }
- @Override
- public long getItemId(int position)
- {
- return super.getItemId(position);
- }
- @Override
- public View getView(final int position, View convertView,
- ViewGroup parent)
- {
- View view = super.getView(position, convertView, parent);
- final CheckBox checkbox = (CheckBox) view.findViewById(mCheckBoxId);
- checkbox.setOnClickListener(new OnClickListener()
- {
- @Override
- public void onClick(View v)
- {
- Cursor cursor = getCursor();
- cursor.moveToPosition(position);
- checkbox.setChecked(checkbox.isChecked());
- if(checkbox.isChecked())//如果被选中则将id保存到集合中
- {
- selection.add(cursor.getInt(cursor.getColumnIndex(mIdColumn)));
- }
- else//否则移除
- {
- selection.remove(new Integer(cursor.getInt(cursor.getColumnIndex(mIdColumn))));
- Toast.makeText(context, "has removed " + cursor.getInt(cursor.getColumnIndex(mIdColumn)), 0).show();
- }
- }
- });
- return view;
- }
- /返回集合
- public ArrayList<Integer> getSelectedItems()
- {
- return selection;
- }
- }
调用:
- List<Integer> bn = XXX.getSelectedItems();
- for(int id : bn)
- {
- //TODO 执行删除操作
- }
如果没能帮到你,试试这篇文章(http://craftsman1970.blog.51cto.com/3522772/725606)。
'차근차근 > Android' 카테고리의 다른 글
[ study ] 다이어리 어플 만들어보기 2 - 부가설명5 (0) | 2015.05.07 |
---|---|
[ study ] 다이어리 어플 만들어보기 2 (0) | 2015.05.06 |
ListView 소스 (0) | 2015.05.06 |
[ study ] 다이어리 어플 만들어보기 2 - 부가설명4 (0) | 2015.05.06 |
[ study ] 다이어리 어플 만들어보기 2 - 부가설명3 (0) | 2015.05.04 |
'차근차근/Android'의 다른글
- 현재글listview + checkbox