SoFunction
Updated on 2025-03-01

Examples of Android ListView implementing single-choice and multiple-choice functions

This article describes the method of implementing functions such as single-choice and multiple-choice in Android ListView. Share it for your reference, as follows:

I have also encountered adding selection function to ListView's item in the project. For example, an online shopping app has a historical browsing page. Now click on the item single-select/multiple-select and all-select-delete functions for this page.

At that time, the status of the item is also recorded by adding a field of whether to select in the data, and then the status changes and deletion operations are performed based on the corresponding position of this field.

I just looked at the 17 ListView implementation methods in Android API Demos, and found that ListView itself has the single choice we need, the multiple choice function and is quite convenient to implement.

/**
  * Single or multiple-select function ListView
  * @description:
  * @author ldm
  * @date 2016-4-21 10:44:37 AM
  */
public class SingleChoiceList extends ListActivity {
  @Override
  public void onCreate(Bundle savedInstanceState) {
    (savedInstanceState);
    setListAdapter(new ArrayAdapter<String>(this,
        .simple_list_item_single_choice, GENRES));
    final ListView listView = getListView();
    (false);
    (ListView.CHOICE_MODE_SINGLE);// Add this sentence to realize the single-choice function      //(ListView.CHOICE_MODE_MULTIPLE);// Add this sentence to realize the multi-select function  }
  private static final String[] GENRES = new String[] {
    "Action", "Adventure", "Animation", "Children", "Comedy", "Documentary", "Drama",
    "Foreign", "History", "Independent", "Romance", "Sci-Fi", "Television", "Thriller"
  };
}

/**
  * Long press and multiple selection, add selection mode
  * @description:
  * @author ldm
  * @date 2016-4-21 10:47:55 AM
  */
public class ChoiceModeList extends ListActivity {
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    (savedInstanceState);
    ListView lv = getListView();
    (ListView.CHOICE_MODE_MULTIPLE_MODAL);
    (new ModeCallback());
    setListAdapter(new ArrayAdapter<String>(this,
        .simple_list_item_checked, mStrings));
  }
  @Override
  protected void onPostCreate(Bundle savedInstanceState) {
    (savedInstanceState);
    getActionBar().setSubtitle("Long press to start selection");
  }
  private class ModeCallback implements  {
    public boolean onCreateActionMode(ActionMode mode, Menu menu) {
      MenuInflater inflater = getMenuInflater();
      (.list_select_menu, menu);
      ("Select Items");
      setSubtitle(mode);
      return true;
    }
    public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
      return true;
    }
    public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
      switch (()) {
      case :
        (, "Shared " + getListView().getCheckedItemCount() +
            " items", Toast.LENGTH_SHORT).show();
        ();
        break;
      default:
        (, "Clicked " + (),
            Toast.LENGTH_SHORT).show();
        break;
      }
      return true;
    }
    public void onDestroyActionMode(ActionMode mode) {
    }
    public void onItemCheckedStateChanged(ActionMode mode,
        int position, long id, boolean checked) {
      setSubtitle(mode);
    }
    private void setSubtitle(ActionMode mode) {
      final int checkedCount = getListView().getCheckedItemCount();
      switch (checkedCount) {
        case 0:
          (null);
          break;
        case 1:
          ("One item selected");
          break;
        default:
          ("" + checkedCount + " items selected");
          break;
      }
    }
  }
  private String[] mStrings = ;
}

After we use the above methods to select ListView, we can record the corresponding item position and operate the corresponding data.

/**
  * ListView with floating prompt box
  *
  * @description:
  * @author ldm
  * @date 2016-4-21 10:55:51 AM
  */
public class List9 extends ListActivity implements  {
  private final class RemoveWindow implements Runnable {
    public void run() {
      removeWindow();
    }
  }
  private RemoveWindow mRemoveWindow = new RemoveWindow();
  Handler mHandler = new Handler();
  private WindowManager mWindowManager;
  private TextView mDialogText;
  private boolean mShowing;
  private boolean mReady;
  private char mPrevLetter = Character.MIN_VALUE;
  @Override
  public void onCreate(Bundle savedInstanceState) {
    (savedInstanceState);
    mWindowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
    setListAdapter(new ArrayAdapter<String>(this,
        .simple_list_item_1, mStrings));
    getListView().setOnScrollListener(this);
    LayoutInflater inflate = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    mDialogText = (TextView) (.list_position, null);
    ();
    (new Runnable() {
      public void run() {
        mReady = true;
         lp = new (
            LayoutParams.WRAP_CONTENT,
            LayoutParams.WRAP_CONTENT,
            .TYPE_APPLICATION,
            .FLAG_NOT_TOUCHABLE
                | .FLAG_NOT_FOCUSABLE,
            );
        (mDialogText, lp);
      }
    });
  }
  @Override
  protected void onResume() {
    ();
    mReady = true;
  }
  @Override
  protected void onPause() {
    ();
    removeWindow();
    mReady = false;
  }
  @Override
  protected void onDestroy() {
    ();
    (mDialogText);
    mReady = false;
  }
  public void onScroll(AbsListView view, int firstVisibleItem,
      int visibleItemCount, int totalItemCount) {
    if (mReady) {
      char firstLetter = mStrings[firstVisibleItem].charAt(0);
      if (!mShowing && firstLetter != mPrevLetter) {
        mShowing = true;
        ();
      }
      (((Character) firstLetter).toString());
      (mRemoveWindow);
      (mRemoveWindow, 3000);
      mPrevLetter = firstLetter;
    }
  }
  public void onScrollStateChanged(AbsListView view, int scrollState) {
  }
  private void removeWindow() {
    if (mShowing) {
      mShowing = false;
      ();
    }
  }
  private String[] mStrings = new String[] { "Abbaye de Belloc",
      "Abbaye du Mont des Cats", "Abertam", "Abondance", "Ackawi",
      "Acorn", "Adelost", "Affidelice au Chablis", "Afuega'l Pitu",
      "Airag", "Airedale", "Aisy Cendre", "Allgauer Emmentaler",
      "Alverca", "Ambert", "American Cheese", "Ami du Chambertin",
      "Beenleigh Blue", "Beer Cheese", "Bel Paese", "Bergader",
      "Bergere Bleue", "Berkswell", "Beyaz Peynir", "Bierkase",
      "Bishop Kennedy", "Blarney", "Bleu d'Auvergne", "Bleu de Gex",
      "Bleu de Laqueuille", "Bleu de Septmoncel", "Bleu Des Causses",
      "Blue", "Blue Castello", "Blue Rathgore", "Blue Vein (Australian)",
      "Blue Vein Cheeses", "Bocconcini", "Bocconcini (Australian)",
      "Boeren Leidenkaas", "Bonchester", "Bosworth", "Bougon",
      "Boule Du Roves", "Boulette d'Avesnes", "Boursault", "Boursin",
      "Bouyssou", "Bra", "Braudostur", "Breakfast Cheese",
      "Brebis du Lavort", "Brebis du Lochois", "Brebis du Puyfaucon",
      "Bresse Bleu", "Brick", "Brie", "Brie de Meaux", "Brie de Melun",
      "Brillat-Savarin", "Brin", "Brin d' Amour", "Brin d'Amour",
      "Brinza (Burduf Brinza)", "Briquette de Brebis",
      "Briquette du Forez", "Broccio", "Broccio Demi-Affine",
      "Brousse du Rove", "Bruder Basil",
      "Brusselae Kaas (Fromage de Bruxelles)", "Bryndza",
      "Buchette d'Anjou", "Buffalo", "Chevrotin des Aravis",
      "Chontaleno", "Civray", "Coeur de Camembert au Calvados",
      "Coeur de Chevre", "Colby", "Cold Pack", "Comte", "Coolea",
      "Cooleney", "Coquetdale", "Corleggy", "Cornish Pepper",
      "Cotherstone", "Cotija", "Cottage Cheese",
      "Cottage Cheese (Australian)", "Cougar Gold", "Coulommiers",
      "Coverdale", "Crayeux de Roncq", "Cream Cheese", "Cream Havarti",
      "Crema Agria", "Crema Mexicana", "Creme Fraiche", "Crescenza",
      "Croghan", "Crottin de Chavignol", "Crottin du Chavignol",
      "Crowdie", "Crowley", "Cuajada", "Curd", "Cure Nantais",
      "Curworthy", "Cwmtawe Pecorino", "Cypress Grove Chevre",
      "Danablu (Danish Blue)", "Danbo", "Danish Fontina",
      "Daralagjazsky", "Dauphin", "Delice des Fiouves",
      "Denhany Dorset Drum", "Derby", "Dessertnyj Belyj", "Devon Blue",
      "Devon Garland", "Dolcelatte", "Doolin", "Doppelrhamstufel",
      "Dorset Blue Vinney", "Double Gloucester", "Double Worcester",
      "Dreux a la Feuille", "Dry Jack", "Garrotxa", "Gastanberra",
      "Geitost", "Gippsland Blue", "Gjetost", "Gloucester",
      "Golden Cross", "Gorgonzola", "Gornyaltajski", "Gospel Green",
      "Gouda", "Goutu", "Gowrie", "Grabetto", "Graddost",
      "Grafton Village Cheddar", "Grana", "Grana Padano", "Grand Vatel",
      "Grataron d' Areches", "Gratte-Paille", "Graviera", "Greuilh",
      "Greve", "Gris de Lille", "Gruyere", "Gubbeen", "Guerbigny",
      "Halloumi", "Halloumy (Australian)", "Haloumi-Style Cheese",
      "Harbourne Blue", "Havarti", "Heidi Gruyere", "Hereford Hop",
      "Herrgardsost", "Herriot Farmhouse", "Herve", "Hipi Iti",
      "Hubbardston Blue Cow", "Hushallsost", "Iberico", "Idaho Goatster",
      "Idiazabal", "Il Boschetto al Tartufo", "Ile d'Yeu",
      "Isle of Mull", "Jarlsberg", "Jermi Tortes", "Jibneh Arabieh",
      "Jindi Brie", "Jubilee Blue", "Juustoleipa", "Kadchgall", "Kaseri",
      "Kashta", "Kefalotyri", "Kenafa", "Kernhem", "Kervella Affine",
      "Kikorangi", "King Island Cape Wickham Brie", "King River Gold",
      "Klosterkaese", "Knockalara", "Kugelkase", "Menallack Farmhouse",
      "Menonita", "Meredith Blue", "Mesost", "Metton (Cancoillotte)",
      "Meyer Vintage Gouda", "Mihalic Peynir", "Milleens", "Mimolette",
      "Mine-Gabhar", "Mini Baby Bells", "Mixte", "Molbo",
      "Monastery Cheeses", "Mondseer", "Mont D'or Lyonnais", "Montasio",
      "Monterey Jack", "Monterey Jack Dry", "Morbier",
      "Morbier Cru de Montagne", "Mothais a la Feuille", "Mozzarella",
      "Mozzarella (Australian)", "Mozzarella di Bufala",
      "Mozzarella Fresh, in water", "Mozzarella Rolls", "Munster",
      "Murol", "Mycella", "Myzithra", "Peekskill Pyramid",
      "Pelardon des Cevennes", "Pelardon des Corbieres", "Penamellera",
      "Penbryn", "Pencarreg", "Perail de Brebis", "Petit Morin",
      "Petit Pardou", "Petit-Suisse", "Picodon de Chevre",
      "Picos de Europa", "Piora", "Pithtviers au Foin",
      "Plateau de Herve", "Plymouth Cheese", "Podhalanski",
      "Poivre d'Ane", "Polkolbin", "Pont l'Eveque", "Port Nicholson",
      "Port-Salut", "Postel", "Pouligny-Saint-Pierre", "Pourly",
      "Prastost", "Pressato", "Prince-Jean", "Processed Cheddar",
      "Provolone", "Provolone (Australian)", "Pyengana Cheddar",
      "Pyramide", "Quark", "Quark (Australian)", "Quartirolo Lombardo",
      "Quatre-Vents", "Quercy Petit", "Queso Blanco",
      "Queso Blanco con Frutas --Pina y Mango", "Queso de Murcia",
      "Queso del Montsec", "Saint-Marcellin", "Saint-Nectaire",
      "Saint-Paulin", "Salers", "Samso", "San Simon", "Sancerre",
      "Sap Sago", "Sardo", "Sardo Egyptian", "Sbrinz", "Scamorza",
      "Schabzieger", "Schloss", "Selles sur Cher", "Selva", "Serat",
      "Seriously Strong Cheddar", "Serra da Estrela", "Sharpam",
      "Shelburne Cheddar", "Shropshire Blue", "Siraz", "Sirene",
      "Smoked Gouda", "Somerset Brie", "Sonoma Jack",
      "Sottocenare al Tartufo", "Soumaintrain", "Sourire Lozerien",
      "Spenwood", "Sraffordshire Organic", "St. Agur Blue Cheese",
      "Stilton", "Stinking Bishop", "String", "Sussex Slipcote",
      "Sveciaost", "Swaledale", "Sweet Style Swiss", "Swiss",
      "Syrian (Armenian String)", "Tala", "Taleggio", "Tamie",
      "Tasmania Highland Chevre Log", "Taupiniere", "Teifi", "Telemea",
      "Testouri", "Tete de Moine", "Tetilla", "Venaco", "Vendomois",
      "Vieux Corse", "Vignotte", "Vulscombe", "Waimata Farmhouse Blue",
      "Washed Rind Cheese (Australian)", "Waterloo", "Weichkaese",
      "Wellington", "Wensleydale", "White Stilton",
      "Zanetti Parmigiano Reggiano" };
}

For more information about Android related content, please check out the topic of this site:Android control usage summary》、《Android development introduction and advanced tutorial》、《Android View View Tips Summary》、《Android programming activity operation skills summary》、《Android database operation skills summary"and"Android resource operation skills summary

I hope this article will be helpful to everyone's Android programming design.