如何从列表中删除复选框项目

4

我有一个列表,其中有50个列表项。现在我已经勾选了10个项目,那么当我点击删除按钮时,如何从列表视图中删除这10个已勾选的项目。

以下是我的代码:

请查看我的代码并回复哪里出错了:

public class BookmarksJokes extends Activity implements OnClickListener,
    OnItemClickListener {
ListView lv;
Button btn_delete;
public String TAG = "horror";
private SQLiteDatabase db;
public static final String PREFS_NAME = "MyPreferences";
static String[] tempTitle = new String[100];
static String[] tempBody = new String[100];
private static boolean bRequiresResponse;

private static class EfficientAdapter extends BaseAdapter {
    private LayoutInflater mInflater;

    public EfficientAdapter(Context context) {
        mInflater = LayoutInflater.from(context);

    }
    public int getCount() {
        return tempTitle.length;
    }

    public Object getItem(int position) {
        return position;
    }

    public long getItemId(int position) {
        return position;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.bookmarks_list_item,
                    null);
            holder = new ViewHolder();
            holder.text1 = (TextView) convertView
                    .findViewById(R.id.title);
            holder.text2 = (TextView) convertView
                    .findViewById(R.id.body);
             holder.checkBox = (CheckBox) convertView.findViewById(R.id.checkbox);

            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        holder.text1.setText(tempTitle[position]);
        holder.text2.setText(tempBody[position]);
        // bRequiresResponse = checkBox.isChecked();
        return convertView;
    }

    static class ViewHolder {
        TextView text1;
        TextView text2;
        CheckBox checkBox;
    }
}

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.bokmarksjoks);

    try {
        db = (new DatabaseHelper(this)).getWritableDatabase();
    } catch (IOException e) {
        e.printStackTrace();
    }
    setUpViews();

    title = (TextView) findViewById(R.id.body);
    SharedPreferences pref = getSharedPreferences(PREFS_NAME, 0);

    //String ids = pref.getString("jid", "");
    String one = pref.getString("title", "");
    String two = pref.getString("body", "");

    tempTitle = one.split(",");
    tempBody = two.split(",");
    lv.setAdapter(new EfficientAdapter(this));
}

private void setUpViews() {
    lv = (ListView) findViewById(R.id.list);
    btn_delete = (Button) findViewById(R.id.delete);
    btn_delete.setOnClickListener(this);
    // checkbox = (CheckBox) findViewById(R.id.checkbox);

}
private void removeData(){
//int pos= getIntent().getIntExtra("POSITION", 0);
//lv.removeViewAt(pos);
// notifyAll();*/
//  int pos= getIntent().getIntExtra("POSITION", 0);
//  if(checkBox.isChecked()){
//      Log.d(TAG, " checked d]"+pos);
//      Toast.makeText(this, "checked "+pos, Toast.LENGTH_SHORT).show();
//  }
}
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.delete:
        AlertDialog.Builder alt_bld = new AlertDialog.Builder(this);
        alt_bld.setMessage("Are you Sure want to delete all checked jok ?")
                .setCancelable(false)
                .setPositiveButton("Yes",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                    int id) {
                                //removeJok();

                            }
                        })
                .setNegativeButton("No",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                    int id) {
                                dialog.cancel();
                            }
                        });
        AlertDialog alert = alt_bld.create();
        alert.setTitle("Delete Jokes");
        alert.show();
    case R.id.checkbox:

    default:
        break;
    }

}

public void onItemClick(AdapterView<?> arg0, View view, int position,
        long ids) {

    try {

    //   checkBox = (CheckBox)view.findViewById(R.id.checkbox);
    //   checkBox.setChecked(true);

        Intent intent = new Intent(BookmarksJokes.this,
                BookmarkJokesDetails.class);

        intent.putExtra("POSITION", position);
        intent.putExtra("ID", ids);
        Cursor cursor = (Cursor) adapter.getItem(position);

        intent.putExtra("_ID",
                cursor.getInt(cursor.getColumnIndex("_id")));

        startActivity(intent);
    } catch (Exception e) {
        e.printStackTrace();
    }

    Toast.makeText(BookmarksJokes.this,
            "Item in position " + position + " clicked", Toast.LENGTH_LONG)
            .show();
}
}

以下是完整代码:

http://pastebin.com/LB2WKHMP

(注:此处为原文,无需翻译)

作为一个公平的玩家,请查看我的代码。 - Horrorgoogle
6个回答

10

我在我的应用程序中执行了相同的任务。

你应该使用一个ArrayList,它与列表项具有相同的大小,并且每个项目默认包含0。现在在您的Efficient Adapter中,对于每个选中的复选框,在arrayList中分配1到该特定位置。最后,在删除按钮点击时,遍历ArrayList并从包含该位置上为1的所有项目中删除所有这些项目,并最后调用列表的notifyDatasetChanged()方法,以便列表得到更新并显示新列表。

以下是一些示例代码,以便更好地理解:

 ArrayList<Integer> checks=new ArrayList<Integer>();

现在在onCreate方法中

for(int b=0;b<tempTitle.length;b++){
    checks.add(b,0);  //assign 0 by default in each position of ArrayList
        } 

现在在你的 efficientAdapter 的 getView 方法中

 public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.bookmarks_list_item,
                    null);
            holder = new ViewHolder();
            holder.text1 = (TextView) convertView
                    .findViewById(R.id.title);
            holder.text2 = (TextView) convertView
                    .findViewById(R.id.body);
             holder.checkBox = (CheckBox) convertView.findViewById(R.id.checkbox);

            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

           holder.checkBox.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                // TODO Auto-generated method stub

                if(((CheckBox)v).isChecked()){
                  checks.set(position, 1);
                }
                else{
                 checks.set(position, 0);
                }

            }
        });


        return convertView;
    }

最后,在删除按钮点击时:

     delete.setOnClickListener(new OnClickListener() {

    public void onClick(View v) {
    // TODO Auto-generated method stub

          for(int i=0;i<checks.size();i++){

    if(checks.get(i)==1){
          //remove items from the list here for example from ArryList 
          checks.remove(i);
           //similarly remove other items from the list from that particular postion
           i--;
        }
     }
    ((EfficientAdapter)lv.getAdapter()).notifyDataSetChanged();
  }
}
希望这能解决你的问题。

4
我假设我已经得到了所选的ID。现在只需要使用arrayList.remove(position);,然后调用notifyDataSetChanged();即可。

2
伙计,你的代码缺少复选框和对象之间的关系,而且你没有在适配器中实现onCheckedchangeListener.... 你需要的是这个:http://www.vogella.de/articles/AndroidListView/article.html#listadvanced_interactive 或者我可以帮你包装一下。
  1. you'll need to create a class model.java which represents the cell of the list as follows:

    public class Model {
         private String title;
         private String body;
         private boolean isSelected;
    
         public Model(String title, String body) {
              this.title = title;
              this.body = body;
              this.isSelected = false;
         }
    
         // here you MUST create your set of setters and getters.
    }
    
  2. modify your adapter to extend ArrayAdapter<Model>

  3. modify the constructor of the adapter to be

    private Model[] model;
    public EfficientAdapter(Context context, Model model) {
    
         mInflater = LayoutInflater.from(context);
         this.model = model;
    
    }
    
  4. then you'll need to add the onCheckedChangeListener inside your adapter inside the getView method , so your getView method will look like this:

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view = null;
        if (convertView == null) {
            LayoutInflater inflator = context.getLayoutInflater();
    
            final ViewHolder viewHolder = new ViewHolder();
            viewHolder.text1 = (TextView) convertView.findViewById(R.id.title);
            viewHolder.text2 = (TextView) convertView.findViewById(R.id.body);
            viewHolder.checkBox = (CheckBox) convertView.findViewById(R.id.checkbox);
            viewHolder.checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
    
                @Override
                public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
    
                    Model element = (Model) viewHolder.checkbox.getTag();
    
                    element.setSelected(buttonView.isChecked());
                }
            });
            view.setTag(viewHolder);
            viewHolder.checkbox.setTag(list[position]);
        } else {
            view = convertView;
            ((ViewHolder) view.getTag()).checkbox.setTag(list[position]);
        }
    
        ViewHolder holder = (ViewHolder) view.getTag();
        holder.text1.setText(tempTitle[position]);
        holder.text2.setText(tempBody[position]);
        return view;
    }
    
  5. then create the model array inside your activity and pass it to the adapter.

  6. the last thing to be done is to delete the selected items from the list:

    final ArrayList<Model> newModel = new ArrayList<Model>();
    
    for (int i = 0; i < model.length/*this is the original model*/; i++) {
    
        if(model[i].isChecked()){
    
            // fill the array list ...
            newModel.add(model[i]);
        }
    }
    
  7. that's it, pass the newModel to the adapter and rest the adapter to the list.

第七步也可以通过填充模型(最初传递给数组的原始模型)并使用适配器调用 notifyDataSetChanged() 来完成。

以上就是我一直使用的方法,希望对你有所帮助。


0

我认为你的问题不需要大量的代码,只需要一个概念。上面给出的答案是最好的方法。

I am assuming i got ids which are selected. now simply arrayList.remove(position);
and call notifyDataSetChanged();

在列表视图的子项(复选框)中,可以直接在基础适配器类中使用setOnCheckChangesListener。现在,您只需要跟踪选中的复选框及其在ArrayList中对应的位置。当您单击删除按钮时,从ArrayList中删除元素并调用notifyDataSetChanged()。


你解决了吗?如果你还有其他关于如何实现它的疑问,请告诉我们。 - Tofeeq Ahmad

0

当您选择复选框并按下删除按钮时,请再次刷新列表视图。这意味着在删除项目后,您必须将适配器重新设置到列表视图中。谢谢。


0
如果您使用具有CHOICE_MODE_MULTIPLE模式的列表视图,您应该能够使用类似以下的代码: listView.getCheckedItemPositions();
然后,如果您将列表项存储在某种列表或向量中,您应该能够轻松地删除具有相同位置的项目,并更新列表视图。
尽管我所有复选框+列表的知识都基于此: Android list and checkbox

他没有问如何创建多选列表视图。 - Richa
我试图给出一个想法,关于如何删除那些项目,如果他正在使用多选列表视图(他很可能是这样做的)。 - varesa

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接