Using the TListView to select multiple items

Its very easy to create a drop down list using the TComboBox to select a single item, but how can you easily select multiple items from a list across iOS and Android? Once easy way is to use the TListView component in EditMode. To view an example of this, add a TListView to a new form and using the FormCreate add in 20 items using a simple loop.

procedure TForm1.FormCreate(Sender: TObject);
var
  I: Integer;
begin
  ListView1.BeginUpdate;
  try
    for I := 1 to 20 do
      ListView1.Items.Add.Text := I.ToString();
  finally
    ListView1.EndUpdate;
  end;
end;

Also note the use of BeginUpdate and EndUpdate using the Try Finally block to speed up the processing. This prevents the ListView from redrawing between each item add.

Now using two buttons we can add on click events to see how to toggle the EditMode..

procedure TForm1.btnEditClick(Sender: TObject);
begin
  ListView1.EditMode := not ListView1.EditMode;
  (Sender as TButton).Text := 'EditMode '+ListView1.EditMode.ToString(TUseBoolStrs.True);
end;

..and secondly show the selected items.

Each TListViewItem has a Checked property that can be queried to discover if the item is selected. Again using a simple look it is possible to check each item and then add it to a list that we will show.

procedure TForm1.btnShowSelectedClick(Sender: TObject);
var
  SL : TStringList;
  I: Integer;
begin
  if ListView1.Items.CheckedCount = 0 then begin
    ShowMessage('No selected items');
    Exit;
  end;

  SL := TStringList.Create;
  try
    for I := 0 to ListView1.ItemCount -1 do begin
       if ListView1.Items[I].Checked then
         SL.Add(ListView1.Items[I].Text);
    end;
    ShowMessage('Items selected: '+SL.CommaText);
  finally
    SL.Free;
  end;
end;

For simplicity in the code above I have used the TStringList.CommaText to give a formatted output of the data.

ListView Multi-Select on iOS
ListView Multi-Select on iOS
Android ListView Multi-Select
Android ListView Multi-Select

Leave a Reply

Your email address will not be published. Required fields are marked *