我已经实现了一个简单的方法,可以在此解决方案Removing muliple items from listview using Check box in Android之后从列表视图中删除多个项目,然后对其进行一些修改,以便为两个按钮点击事件add
& ; delete
。问题是当我点击删除按钮时,应用崩溃会给我这些错误:http://pastebin.com/2NmCQk2B
我不知道为什么我得到空指针异常,因为我相信我已正确分配了所有内容。
有人可以更好地解释为什么我会收到此错误吗?或者也许是从列表视图中删除所选订单项的更好方法?
完整的课程发布在下面,以便更好地理解:
public class TopRatedFragment extends Fragment implements OnClickListener {
ListView mListView;
EditText mValue;
Button mAdd,mDel;
ArrayList<String> list = new ArrayList<String>();
ArrayAdapter<String> adapter;
SparseBooleanArray mCheckStates ;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_top_rated, container, false);
mAdd = (Button)rootView.findViewById(R.id.newList);
mDel = (Button)rootView.findViewById(R.id.delBtn);
mAdd.setOnClickListener(this);
mDel.setOnClickListener(this);
mValue = (EditText)rootView.findViewById(R.id.listData);
adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_expandable_list_item_1, list);
// set the lv variable to your list in the xml
mListView=(ListView)rootView.findViewById(R.id.listView);
mListView.setAdapter(adapter);
return rootView;
}
public void onClick(View v)
{
switch(v.getId()){
case R.id.newList:
//DO something
String input = mValue.getText().toString();
if(input.length() > 0)
{
// add string to the adapter, not the listview
adapter.add(input);
// no need to call adapter.notifyDataSetChanged(); as it is done by the adapter.add() method
}
break;
case R.id.delBtn:
//DO something
SparseBooleanArray checked = mListView.getCheckedItemPositions();
for (int i = 0; i < mListView.getCount(); i++){
//line 65
if (checked.get(i)==true)
{
list.remove(i);
}
adapter.notifyDataSetChanged();
}
mListView.clearChoices();
}
}
}
答案 0 :(得分:1)
从适配器中删除而不是从listview中尝试以下操作:
SparseBooleanArray checked = mListView.getCheckedItemPositions();
if(checked!=null){
for (int i = 0; i < mListView.getCount(); i++){
//line 65
if (checked.get(i)==true)
{
adapter.remove(mListView.getItemAtPosition(i));
}
adapter.notifyDataSetChanged();
}
mListView.clearChoices();
}
getCheckedItemPositions返回: SparseBooleanArray,对于get(int position)的每个调用都将返回true,其中position是列表中的已检查位置,否则为false;如果选择模式设置为CHOICE_MODE_NONE,则返回null。
答案 1 :(得分:1)
您需要使用valueAt(),工作代码应为
SparseBooleanArray checkedItems = mListView.getCheckedItemPositions();
if (checkedItems != null) {
for (int i=0; i<checkedItems.size(); i++) {
if (checkedItems.valueAt(i)) {
String item = mListView.getAdapter().getItem(
checkedItems.keyAt(i)).toString();
Log.i(TAG,item + " was selected");
}
}
}
答案 2 :(得分:0)
我用这种方式循环,它起作用了:
SparseBooleanArray checkedItemPositions = getListView().getCheckedItemPositions();
int itemCount = getListView().getCount();
for(int i=itemCount-1; i >= 0; i--){
if(checkedItemPositions.get(i)){
adapter.remove(list.get(i));
}
}
checkedItemPositions.clear();
adapter.notifyDataSetChanged();