w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Remove multiple items from List view except Selected items

The standard way to do such actions is to use Action mode of action bar.

Anyways, Here's an example:

DataModel: This exposes data manipulation methods to local code. Here its just using in-memory data structures, but in real applications, it can be backed by a database or a web service or something else.

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

public class DataModel {
    private static DataModel ourInstance = new DataModel();

    private final List<String> mPersons;
    private final HashMap<String,Set<String>> mGroups;

    public static DataModel getInstance() {
        return ourInstance;
    }

    private DataModel() {
        mPersons = new ArrayList<String>();
        mGroups = new HashMap<String, Set<String>>();

        for (int i = 0; i < 50; i++){
            mPersons.add("person_"+i);
        }
    }

    public void updateGroup(String oldName, String newName,
Set<String> members){
        assert  newName != null && !newName.isEmpty() &&
members != null : "data must not be null or empty";

        if(oldName != null){
            mGroups.remove(oldName);
        }

        mGroups.put(newName, members);
    }

    public void deleteGroup(String name){
        mGroups.remove(name);
    }

    public boolean isMember(String groupName, String memberName){
        return mGroups.containsKey(groupName) &&
mGroups.get(groupName).contains(memberName);
    }

    public List<String> getGroups(){
        List<String> groups = new ArrayList<String>();

        for (String s : mGroups.keySet()){
            groups.add(s);
        }

        return groups;
    }

    public List<String> getMembersOf(String groupName){
        List<String> members = new ArrayList<String>();

        if(mGroups.containsKey(groupName)){
            members.addAll(mGroups.get(groupName));
        }

        return members;
    }

    public List<String> getPersons(){
        List<String> persons = new ArrayList<String>();
        persons.addAll(mPersons);
        return persons;
    }
}

Activity to List data: Allows action mode by long clicking any item, or edit an item by clicking on it.

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;

import java.util.ArrayList;
import java.util.List;

public class GroupActivity extends ListActivity implements
AbsListView.MultiChoiceModeListener, AdapterView.OnItemClickListener {
    public static final int REQ_CODE_EDIT_GROUP = 101;

    private List<String> mSelection;
    private ArrayAdapter<String> mAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mSelection = new ArrayList<String>();
        mAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_activated_1);

        mAdapter.addAll(DataModel.getInstance().getGroups());

        setListAdapter(mAdapter);
       
getListView().setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE_MODAL);
        getListView().setMultiChoiceModeListener(this);
        getListView().setOnItemClickListener(this);
    }

    private void refresh(){
        mAdapter.clear();
        mAdapter.addAll(DataModel.getInstance().getGroups());
        mAdapter.notifyDataSetInvalidated();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuItem item = menu.add("New");
        item.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if(item.getTitle().equals("New")){
            startEditor(null);
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void startEditor(String groupName){
        Intent i = new Intent(this,EditorActivity.class);

        if(groupName != null){
            i.putExtra(EditorActivity.KEY_EDIT_GROUP,groupName);
        }

        startActivityForResult(i,REQ_CODE_EDIT_GROUP);
    }

    @Override
    public void onItemCheckedStateChanged(ActionMode actionMode, int i,
long l, boolean checked) {
        if(checked){
            mSelection.add(mAdapter.getItem(i));
        }else {
            mSelection.remove(mAdapter.getItem(i));
        }
    }

    @Override
    public boolean onCreateActionMode(ActionMode actionMode, Menu menu) {
        MenuItem item = menu.add("Delete");
        item.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
        return true;
    }

    @Override
    public boolean onPrepareActionMode(ActionMode actionMode, Menu menu) {
        return false;
    }

    @Override
    public boolean onActionItemClicked(ActionMode actionMode, MenuItem
menuItem) {
        if(menuItem.getTitle().equals("Delete")){

            for (String groupName : mSelection){
                DataModel.getInstance().deleteGroup(groupName);
            }

            refresh();
            actionMode.finish();
            return true;
        }else {
            return false;
        }
    }

    @Override
    public void onDestroyActionMode(ActionMode actionMode) {
        mSelection.clear();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent
data) {

        if(requestCode == REQ_CODE_EDIT_GROUP && resultCode ==
RESULT_OK){
            refresh();
        }else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view,
int i, long l) {
        String groupName = mAdapter.getItem(i);
        startEditor(groupName);
    }
}

Activity to edit data : Allows editing names and selections etc.

It has a Layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

<EditText
     android:id="@+id/edit"
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:hint="Group name"
     android:inputType="text"/>
    <ListView
        android:id="@+id/list"
        android:layout_width="match_parent"
        android:layout_height="fill_parent"
        />
</LinearLayout>

And Activity code:

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.*;

import java.util.HashSet;


public class EditorActivity extends Activity {
    public static final String KEY_EDIT_GROUP = "edit_group";

    private EditText mNameEdit;
    private ListView mListView;
    private ArrayAdapter<String> mAdapter;
    private String mOldGroupName;

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

        mNameEdit = (EditText) findViewById(R.id.edit);
        mListView = (ListView) findViewById(R.id.list);

        mListView.setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE);

        mAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_activated_1);
        mAdapter.addAll(DataModel.getInstance().getPersons());
        mListView.setAdapter(mAdapter);

        mOldGroupName = getIntent().getStringExtra(KEY_EDIT_GROUP);

        if(mOldGroupName != null){
            mNameEdit.setText(mOldGroupName);

            for (int i = 0 ; i < mAdapter.getCount(); i++){
                DataModel dm = DataModel.getInstance();
                String member = mAdapter.getItem(i);

                if(dm.isMember(mOldGroupName,member)){
                    mListView.setItemChecked(i,true);
                }
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuItem item = menu.add("Done");
        item.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if(item.getTitle().equals("Done")){

            String newGroupName = mNameEdit.getText().toString();

            if(newGroupName == null || newGroupName.isEmpty()){
                Toast.makeText(this,"Invalid group
name",Toast.LENGTH_LONG).show();
                return true;
            }

            HashSet<String> selectedMembers = new
HashSet<String>();
            for (int i = 0 ; i < mAdapter.getCount(); i++){
                if(mListView.isItemChecked(i)){
                    selectedMembers.add(mAdapter.getItem(i));
                }
            }

           
DataModel.getInstance().updateGroup(mOldGroupName,newGroupName,selectedMembers);

            setResult(RESULT_OK);
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}




© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.