I've a couple of question I haven't been able to figure out.
我有几个问题没弄清楚。
I'm trying to get all the checked elements from a ListView
but:
我试图从ListView中获取所有被检查的元素,但是:
-
If I check and then uncheck an element, it's returned as "checked" by the
getCheckedItemPositions()
function如果我检查然后取消检查一个元素,它会被getCheckedItemPositions()函数作为“检查”返回
-
I don't know how can I iterate through this:
我不知道该怎么重复这个:
SparseBooleanArray checked = list.getCheckedItemPositions();
9 个解决方案
#1
74
The other answers using SparseBooleanArray
are nearly correct, but they are missing one important thing: SparseBooleanArray.size()
will sometimes only return the count of true
values. A correct implementation that iterates over all the items of the list is:
使用SparseBooleanArray的其他答案几乎是正确的,但是它们忽略了一件重要的事情:SparseBooleanArray.size()有时只返回真实值的计数。迭代列表中所有项目的正确实现是:
SparseBooleanArray checked = list.getCheckedItemPositions();
for (int i = 0; i < list.getAdapter().getCount(); i++) {
if (checked.get(i)) {
// Do something
}
}
#2
11
I solved my case with this:
我用这个解决了我的案子
public class MyAdapter extends BaseAdapter{
public HashMap<String,String> checked = new HashMap<String,String>();
....
public void setCheckedItem(int item) {
if (checked.containsKey(String.valueOf(item))){
checked.remove(String.valueOf(item));
}
else {
checked.put(String.valueOf(item), String.valueOf(item));
}
}
public HashMap<String, String> getCheckedItems(){
return checked;
}
}
To set an element is checked:
要设置一个元素,请检查:
public class FileBrowser extends Activity implements OnClickListener{
private ListView list;
...
list.setOnItemClickListener(new OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> parent, View view, int item,
long id) {
BrowserAdapter bla = (BrowserAdapter) parent.getAdapter();
bla.setCheckedItem(item);
}
});
Then to get the checked items from outside the class..
然后从类外部获取已检查的项。
MyAdapter bAdapter;
Iterator<String> it = bAdapter.getCheckedItems().values().iterator();
for (int i=0;i<bAdapter.getCheckedItems().size();i++){
//Do whatever
bAdapter.getItem(Integer.parseInt(it.next());
}
Hope it can help someone.
希望它能帮助某人。
#3
7
Jarett's answer is great, but this should be a bit faster, since it's only checking the elements in the sparse array that are present in the underlying array (only those can be true):
Jarett的答案很好,但是这应该快一点,因为它只检查底层数组中稀疏数组中的元素(只有那些是正确的):
SparseBooleanArray checkedItemPositions = listView.getCheckedItemPositions();
final int checkedItemCount = checkedItemPositions.size();
for (int i = 0; i < checkedItemCount; i++) {
int key = checkedItemPositions.keyAt(i);
if (checkedItemPositions.get(key)) {
doSomething(key);
} else {
// item was in the sparse array, but not checked.
}
}
Pro tip: look at the source of SparseBooleanArray, it's a pretty simple class:
专业提示:看看SparseBooleanArray的来源,它是一个非常简单的类:
http://grepcode.com/file_/repository.grepcode.com/java/ext/com.google.android/android/4.0.3_r1/android/util/SparseBooleanArray.java/?v=source
#4
6
You can iterate through the SparseBooleanArray using a for loop and the SparseBooleanArray's size() and get(index) methods.
您可以使用for循环和SparseBooleanArray的size()和get(index)方法遍历SparseBooleanArray。
EDIT 3/2/2014: People have pointed out that SparseBooleanArray's size() method returns the number of checked values, rather than the true length of the array, so I have mended my answer to account for that. Essentially it is the same, except that rather than iterating for the length of the array, we iterate until we have found all checked items. Since we only care about the number of checked items, it's irrelevant that with this method, we may not actually get to the end of the array (we won't see anything past the last checked item).
编辑3/2/2014:人们已经指出,SparseBooleanArray的size()方法返回选中的值的数量,而不是数组的真实长度,所以我已经修改了我的答案来解释这个问题。本质上它是相同的,只是我们不是迭代数组的长度,而是迭代直到找到所有已检查的项。由于我们只关心已检查项的数量,因此与此方法无关,我们实际上可能不会到达数组的末尾(我们不会看到任何超出最后已检查项的内容)。
SparseBooleanArray checked = list.getCheckedItemPositions();
int numChecked = checked.size();
for (int i = 0; numChecked > 0; i++){
if (checked.get(i)){
//the item at index i is checked, do something
numChecked--; //We found a checked item, so decrement the number of checked items remaining
}
else
//the item is not checked, do something else
}
#5
5
My brain didn't like looping through the SparseBooleanArray and I didn't need a custom adapter, so the following was a little more intuitive for me:
我的大脑不喜欢在SparseBooleanArray中循环,我不需要自定义适配器,所以下面的内容对我来说更直观一些:
-
Don't forget to use CHOICE_MODE_MULTIPLE in onCreate():
不要忘记在onCreate()中使用CHOICE_MODE_MULTIPLE:
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
-
Use the following method to get an ArrayList of them:
使用下面的方法获得一个ArrayList:
// This example is to get an ArrayList of names (Strings) protected ArrayList<String> getNames() { ArrayList<String> names = new ArrayList<String>(); for (int i = 0; i < getListView().getCount(); i++) { if (getListView().isItemChecked(i)) { // Do whatever you need to in here to get data from // the item at index i in the ListView names.add(mUsers.get(i).getName()); } } return names; }
#6
2
final long[] checkedIds = lv.getCheckItemIds();
for (int i = 0; i < checkedIds.length; i++) {
Log.d("checkedIds", "id checked: " + checkedIds[i]);
}
#7
1
Just saw the question and I was facing the same problem.
刚看到这个问题,我也遇到了同样的问题。
There is a simpler solution using SparseBooleanArray to exactly count how many items are checked. This is my onClick procedure:
有一种更简单的解决方案使用SparseBooleanArray来精确地计算检查了多少项。这是我的onClick程序:
@Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.button:
SparseBooleanArray a = listView.getCheckedItemPositions();
if(checked(vArray)>0) {
String vCheckedList = "";
for (int i = 0; i < nLength; i++) {
if (a.valueAt(i) && i < nLength-1 && a.size()>1)
vCheckedList += listView.getAdapter().getItem(vArray.keyAt(i))+"\n";
else if (a.valueAt(i))
vCheckedList += listView.getAdapter().getItem(vArray.keyAt(i));
}
Toast.makeText(getApplicationContext(), vCheckedList+ " is checked", Toast.LENGTH_SHORT).show();
a.clear();
} else
Toast.makeText(getApplicationContext(), "No Item is Selected", Toast.LENGTH_SHORT).show();
break;
default:
break;
}
}
The checked method:
检查方法:
private int checked(SparseBooleanArray vArray) {
int vCounter = 0;
for(int i=0;i<vArray.size(); i++)
if(vArray.valueAt(i))
vCounter++;
return vCounter;
}
It will solve both problem of the checked items.
它将解决检查项目的两个问题。
#8
1
I had the same problem and here is my solution with SparseBooleanArray
:
我也遇到了同样的问题,下面是我对SparseBooleanArray的解决方案:
SparseBooleanArray checkedPositions = lv.getCheckedItemPositions ();
int size = checkedPositions.size ();
for (int i=0 ; i<size ; i++) {
// We get the key stored at the index 'i'
int key = checkedPositions.keyAt (i);
// We get the boolean value with the key
Log.i (Tag, "checkedPositions(" + key + ")=" + checkedPositions.get (key));
}
#9
0
In it's entirety this is the solution I used.
Where pos is the Recyclerview item position
在哪里pos是可回收的项目位置?
SparseBooleanArray selected = new SparseBooleanArray();
//OnClick listener here or whatever you use to check or uncheck an item
if (selected.get(pos, false)) {
selected.delete(pos);
} else {
selected.put(pos, true);
}
selected.size()
will reveal how many items are selected
size()将显示选择了多少项。
selected.get(pos)
will return true if it's selected
如果选择了,get(pos)将返回true。
The following as has been stated, iterates over all those items which were selected:
如前所述,对所选的所有项目进行迭代:
for (int i = 0; i < list.getAdapter().getCount(); i++) {
if (selected.get(pos)) {
// Do stuff
}
}
#1
74
The other answers using SparseBooleanArray
are nearly correct, but they are missing one important thing: SparseBooleanArray.size()
will sometimes only return the count of true
values. A correct implementation that iterates over all the items of the list is:
使用SparseBooleanArray的其他答案几乎是正确的,但是它们忽略了一件重要的事情:SparseBooleanArray.size()有时只返回真实值的计数。迭代列表中所有项目的正确实现是:
SparseBooleanArray checked = list.getCheckedItemPositions();
for (int i = 0; i < list.getAdapter().getCount(); i++) {
if (checked.get(i)) {
// Do something
}
}
#2
11
I solved my case with this:
我用这个解决了我的案子
public class MyAdapter extends BaseAdapter{
public HashMap<String,String> checked = new HashMap<String,String>();
....
public void setCheckedItem(int item) {
if (checked.containsKey(String.valueOf(item))){
checked.remove(String.valueOf(item));
}
else {
checked.put(String.valueOf(item), String.valueOf(item));
}
}
public HashMap<String, String> getCheckedItems(){
return checked;
}
}
To set an element is checked:
要设置一个元素,请检查:
public class FileBrowser extends Activity implements OnClickListener{
private ListView list;
...
list.setOnItemClickListener(new OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> parent, View view, int item,
long id) {
BrowserAdapter bla = (BrowserAdapter) parent.getAdapter();
bla.setCheckedItem(item);
}
});
Then to get the checked items from outside the class..
然后从类外部获取已检查的项。
MyAdapter bAdapter;
Iterator<String> it = bAdapter.getCheckedItems().values().iterator();
for (int i=0;i<bAdapter.getCheckedItems().size();i++){
//Do whatever
bAdapter.getItem(Integer.parseInt(it.next());
}
Hope it can help someone.
希望它能帮助某人。
#3
7
Jarett's answer is great, but this should be a bit faster, since it's only checking the elements in the sparse array that are present in the underlying array (only those can be true):
Jarett的答案很好,但是这应该快一点,因为它只检查底层数组中稀疏数组中的元素(只有那些是正确的):
SparseBooleanArray checkedItemPositions = listView.getCheckedItemPositions();
final int checkedItemCount = checkedItemPositions.size();
for (int i = 0; i < checkedItemCount; i++) {
int key = checkedItemPositions.keyAt(i);
if (checkedItemPositions.get(key)) {
doSomething(key);
} else {
// item was in the sparse array, but not checked.
}
}
Pro tip: look at the source of SparseBooleanArray, it's a pretty simple class:
专业提示:看看SparseBooleanArray的来源,它是一个非常简单的类:
http://grepcode.com/file_/repository.grepcode.com/java/ext/com.google.android/android/4.0.3_r1/android/util/SparseBooleanArray.java/?v=source
#4
6
You can iterate through the SparseBooleanArray using a for loop and the SparseBooleanArray's size() and get(index) methods.
您可以使用for循环和SparseBooleanArray的size()和get(index)方法遍历SparseBooleanArray。
EDIT 3/2/2014: People have pointed out that SparseBooleanArray's size() method returns the number of checked values, rather than the true length of the array, so I have mended my answer to account for that. Essentially it is the same, except that rather than iterating for the length of the array, we iterate until we have found all checked items. Since we only care about the number of checked items, it's irrelevant that with this method, we may not actually get to the end of the array (we won't see anything past the last checked item).
编辑3/2/2014:人们已经指出,SparseBooleanArray的size()方法返回选中的值的数量,而不是数组的真实长度,所以我已经修改了我的答案来解释这个问题。本质上它是相同的,只是我们不是迭代数组的长度,而是迭代直到找到所有已检查的项。由于我们只关心已检查项的数量,因此与此方法无关,我们实际上可能不会到达数组的末尾(我们不会看到任何超出最后已检查项的内容)。
SparseBooleanArray checked = list.getCheckedItemPositions();
int numChecked = checked.size();
for (int i = 0; numChecked > 0; i++){
if (checked.get(i)){
//the item at index i is checked, do something
numChecked--; //We found a checked item, so decrement the number of checked items remaining
}
else
//the item is not checked, do something else
}
#5
5
My brain didn't like looping through the SparseBooleanArray and I didn't need a custom adapter, so the following was a little more intuitive for me:
我的大脑不喜欢在SparseBooleanArray中循环,我不需要自定义适配器,所以下面的内容对我来说更直观一些:
-
Don't forget to use CHOICE_MODE_MULTIPLE in onCreate():
不要忘记在onCreate()中使用CHOICE_MODE_MULTIPLE:
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
-
Use the following method to get an ArrayList of them:
使用下面的方法获得一个ArrayList:
// This example is to get an ArrayList of names (Strings) protected ArrayList<String> getNames() { ArrayList<String> names = new ArrayList<String>(); for (int i = 0; i < getListView().getCount(); i++) { if (getListView().isItemChecked(i)) { // Do whatever you need to in here to get data from // the item at index i in the ListView names.add(mUsers.get(i).getName()); } } return names; }
#6
2
final long[] checkedIds = lv.getCheckItemIds();
for (int i = 0; i < checkedIds.length; i++) {
Log.d("checkedIds", "id checked: " + checkedIds[i]);
}
#7
1
Just saw the question and I was facing the same problem.
刚看到这个问题,我也遇到了同样的问题。
There is a simpler solution using SparseBooleanArray to exactly count how many items are checked. This is my onClick procedure:
有一种更简单的解决方案使用SparseBooleanArray来精确地计算检查了多少项。这是我的onClick程序:
@Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.button:
SparseBooleanArray a = listView.getCheckedItemPositions();
if(checked(vArray)>0) {
String vCheckedList = "";
for (int i = 0; i < nLength; i++) {
if (a.valueAt(i) && i < nLength-1 && a.size()>1)
vCheckedList += listView.getAdapter().getItem(vArray.keyAt(i))+"\n";
else if (a.valueAt(i))
vCheckedList += listView.getAdapter().getItem(vArray.keyAt(i));
}
Toast.makeText(getApplicationContext(), vCheckedList+ " is checked", Toast.LENGTH_SHORT).show();
a.clear();
} else
Toast.makeText(getApplicationContext(), "No Item is Selected", Toast.LENGTH_SHORT).show();
break;
default:
break;
}
}
The checked method:
检查方法:
private int checked(SparseBooleanArray vArray) {
int vCounter = 0;
for(int i=0;i<vArray.size(); i++)
if(vArray.valueAt(i))
vCounter++;
return vCounter;
}
It will solve both problem of the checked items.
它将解决检查项目的两个问题。
#8
1
I had the same problem and here is my solution with SparseBooleanArray
:
我也遇到了同样的问题,下面是我对SparseBooleanArray的解决方案:
SparseBooleanArray checkedPositions = lv.getCheckedItemPositions ();
int size = checkedPositions.size ();
for (int i=0 ; i<size ; i++) {
// We get the key stored at the index 'i'
int key = checkedPositions.keyAt (i);
// We get the boolean value with the key
Log.i (Tag, "checkedPositions(" + key + ")=" + checkedPositions.get (key));
}
#9
0
In it's entirety this is the solution I used.
Where pos is the Recyclerview item position
在哪里pos是可回收的项目位置?
SparseBooleanArray selected = new SparseBooleanArray();
//OnClick listener here or whatever you use to check or uncheck an item
if (selected.get(pos, false)) {
selected.delete(pos);
} else {
selected.put(pos, true);
}
selected.size()
will reveal how many items are selected
size()将显示选择了多少项。
selected.get(pos)
will return true if it's selected
如果选择了,get(pos)将返回true。
The following as has been stated, iterates over all those items which were selected:
如前所述,对所选的所有项目进行迭代:
for (int i = 0; i < list.getAdapter().getCount(); i++) {
if (selected.get(pos)) {
// Do stuff
}
}