3

So far, I have managed to follow this tutorial and run it successfully. But what I wanna do now is to actually delete selected items on my listview. This is the code I'm using:

private String[] data = {"One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine","Ten"};

private SelectionAdapter mAdapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mAdapter = new SelectionAdapter(this,
                R.layout.row_list_item, R.id.textView1, data);
    setListAdapter(mAdapter);
    getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);

    getListView().setMultiChoiceModeListener(new MultiChoiceModeListener() {

        private int nr = 0;

        @Override
        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
            // TODO Auto-generated method stub
            return false;
        }

        @Override
        public void onDestroyActionMode(ActionMode mode) {
            // TODO Auto-generated method stub
             mAdapter.clearSelection();
        }

        @Override
        public boolean onCreateActionMode(ActionMode mode, Menu menu) {
            // TODO Auto-generated method stub

            nr = 0;
            MenuInflater inflater = getMenuInflater();
            inflater.inflate(R.menu.contextual_menu, menu);
            return true;
        }

        @Override
        public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
            // TODO Auto-generated method stub
            switch (item.getItemId()) {

                case R.id.item_delete:
                    nr = 0;
                    mAdapter.clearSelection();
                    mode.finish();
            }
            return true;
        }

        @Override
        public void onItemCheckedStateChanged(ActionMode mode, int position,
                long id, boolean checked) {
            // TODO Auto-generated method stub
             if (checked) {
                    nr++;
                    mAdapter.setNewSelection(position, checked);                   
                } else {
                    nr--;
                    mAdapter.removeSelection(position);                
                }
                mode.setTitle(nr + " selected");

        }
    });

    getListView().setOnItemLongClickListener(new OnItemLongClickListener() {

        @Override
        public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
                int position, long arg3) {
            // TODO Auto-generated method stub

            getListView().setItemChecked(position, !mAdapter.isPositionChecked(position));
            return false;
        }
    });
}

private class SelectionAdapter extends ArrayAdapter<String> {

    private HashMap<Integer, Boolean> mSelection = new HashMap<Integer, Boolean>();

    public SelectionAdapter(Context context, int resource,
            int textViewResourceId, String[] objects) {
        super(context, resource, textViewResourceId, objects);
    }

    public void setNewSelection(int position, boolean value) {
        mSelection.put(position, value);
        notifyDataSetChanged();
    }

    public boolean isPositionChecked(int position) {
        Boolean result = mSelection.get(position);
        return result == null ? false : result;
    }

    public Set<Integer> getCurrentCheckedPosition() {
        return mSelection.keySet();
    }

    public void removeSelection(int position) {
        mSelection.remove(position);
        notifyDataSetChanged();
    }

    public void clearSelection() {
        mSelection = new HashMap<Integer, Boolean>();
        notifyDataSetChanged();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View v = super.getView(position, convertView, parent);//let the adapter handle setting up the row views
        v.setBackgroundColor(getResources().getColor(android.R.color.background_light)); //default color

        if (mSelection.get(position) != null) {
            v.setBackgroundColor(getResources().getColor(android.R.color.holo_blue_light));// this is a selected position so make it red
        }
        return v;
    }
}

Question is how do I delete the selected item/s? I can't figure it out and if anyone of you knows this and can help, I'd gladly appreciate it. Thanks.

4 Answers 4

1

In your code instead of using string [] data you can use ArrayList<String> data since it is dynamically sized array where the object is actually removed and the list (array) size is adjusted accordingly. With this change you can use following method.

@Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
        List<Integer> keyList = new ArrayList<Integer>(noteAdptr.getCurrentCheckedPosition());

        Collections.sort(keyList, new Comparator<Integer>() {

            @Override
            public int compare(Integer lhs, Integer rhs) {

                return lhs.compareTo(rhs);

            }
        });
        Collections.reverse(keyList);

        switch (item.getItemId()) {

            case R.id.item_delete:
                nr = 0;
                for (Integer i:keyList){
                Log.e("", "items selected is : "+i);
                data.remove((int)i);
                }
                mAdapter .notifyDataSetChanged();  
                mAdapter.clearSelection();
                mode.finish();
        }
        return true;
    }

Hope this helps

0

You can set a OnLongClickListener on the items in the ListView that just gets the item that is long pressed.

Afterwards you can reference/remove that object in your OnActionItemClicked.

1
  • 1
    Can you provide some sample implementation of that? THanks.
    – Dunkey
    Feb 6, 2014 at 9:27
0

I am not sure if you have already solved your problem, but here is what worked for me:

  1. Create a private (or public) variable in your class: private int selectedPosition;
  2. In your onItemLongClick() method (as far as I see that's the one, where you are selecting an item), put:

    selectedPosition = position;

  3. in OnActionItemClicked() you can get your adapter and do this:

    MyAdapter adapter = (MyAdapter) this.getAdapter(); adapter.remove(adapter.getItem(selectedPosition);

    adapter.notifyDataSetChanged();

That way you passed the position of the selected item to your adapter.

Hope that helps!

2
  • Hello i tried this one but I'm getting unsupportedoperationexception
    – Dunkey
    Feb 26, 2014 at 8:57
  • hmm interesting. Did you make your variable public or private? maybe you can post an example of what you did
    – lulu
    Feb 26, 2014 at 17:56
0

You have to code the functionality yourself: in the onActionItemClicked, you have to code the logic that will erase selected items from your ArrayList.

Don't forget to call notifyDatasetChanged() on your adapter after that... ;-)

1
  • okay I'm doing that, but my question is how to get the selected positions?
    – Dunkey
    Feb 6, 2014 at 8:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.