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

时间:2012-01-26 10:27:29

标签: android list checkbox

我在列表中有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

6 个答案:

答案 0 :(得分:10)

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

您应该使用与列表项具有相同大小的 ArrayList ,默认情况下每个项目包含0。现在,在您选中的每个复选框的高效适配器中,在arrayList中的特定位置分配1。最后在按钮上单击delete,遍历ArrayList并从列表中删除所有那些在该ArrayList中包含该位置的项目,并在最后调用 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();
  }
}

希望这能解决您的问题。

答案 1 :(得分:4)

我假设我有被选中的ID。 现在只需arrayList.remove(position);和 调用notifyDataSetChanged();

答案 2 :(得分:2)

man,你的代码缺少复选框和对象之间的关系,你也没有在你的适配器中实现onCheckedchangeListener .... 这就是你需要的http://www.vogella.de/articles/AndroidListView/article.html#listadvanced_interactive 或者我会为你包装

  1. 您需要创建一个类model.java,它表示列表的单元格,如下所示:

    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. 修改您的适配器以扩展ArrayAdapter<Model>

  3. 将适配器的构造函数修改为

    private Model[] model;
    public EfficientAdapter(Context context, Model model) {
    
         mInflater = LayoutInflater.from(context);
         this.model = model;
    
    }
    
  4. 然后您需要在onCheckedChangeListener方法中的适配器中添加getView,因此您的getView方法将如下所示:

    @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. 然后在您的活动中创建模型数组并将其传递给适配器。

  6. 要做的最后一件事是从列表中删除所选项目:

    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. 就是这样,将newModel传递给适配器并将适配器放到列表中。

  8. 步骤编号7也可以通过填充模型(最初传递给数组的原始模型)执行,然后使用适配器调用notifyDataSetChanged()

    这就是全部,这对我来说总是有用...希望这对你也有帮助。

答案 3 :(得分:0)

如果您使用带有CHOICE_MODE_MULTIPLE模式的列表视图,您应该可以使用以下内容: listView.getCheckedItemPositions();

然后,如果您将列表项存储在某种列表或向量中,您应该能够轻松删除具有相同位置的项目,并更新列表视图。

尽管我所有的复选框+列表知识都基于此: Android list and checkbox

答案 4 :(得分:0)

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

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

作为List视图子子(CheckBox)可以直接在基类Adapter类中使用setOnCheckChangesListener。现在你只需要在ArrayList.now中保持check复选框及其对应位置的跟踪记录,当你点击delete btn然后从arraylist中删除元素并调用notifyDataSetChanged()

答案 5 :(得分:0)

选中复选框并按下删除按钮后,再次刷新列表视图。表示您必须在删除项目后再次将适配器设置为列表视图。感谢

相关问题