delphi firemonkey使用 TListbox 自定义列表数据(一代码方式实现)

界面设计如下

启动时默认值

procedure TForm1.FormCreate(Sender: TObject);
begin
  //启动时隐藏模板
  Layout1.Visible := False;
  //开启隔行变色
  ListBox1.AlternatingRowBackground := True;
end;

Listbox添加Item代码如下

procedure TForm1.AddItem(name: string; age: Integer; img: string);
var
  layout: TLayout;
  item: TListBoxItem;
begin
  //设置Label3和Label4标签的文本
  Label3.Text := name;
  Label4.Text := IntToStr(age);

  //创建一个新的ListBoxItem
  item := TListBoxItem.Create(ListBox1);
  //设置ListBoxItem的宽度与高度
  item.Width := ListBox1.Width;
  item.Height := Layout1.Height + 12;
  item.Selectable := False;

  //复制Layout1控件,并将其与item关联
  layout := TLayout(Layout1.Clone(item));
  layout.Align := TAlignLayout.Client;
  layout.Visible := True;

  //如果图片存在,则加载图片
  if FileExists(img) then
    ImageControl1.Bitmap.LoadFromFile(img);

  //设置ListBoxItem的边距
  item.Padding.Left := 5;
  item.Padding.Top := 5;
  item.Padding.Bottom := 5;
  item.Padding.Right := 5;

  //将layout添加到item中,并将item添加到ListBox1中
  item.AddObject(layout);
  ListBox1.AddObject(item);
end;

添加项目

procedure TForm1.Button1Click(Sender: TObject);
begin
  ListBox1.Items.Clear;
  for var i := 0 to 20 do
  begin
    AddItem('zhangsan-' + IntToStr(i), Random(100), 'D:\People\' + IntToStr(Random(9) + 1) + '.png');
  end;
end;

完成后界面如下

 

posted @ 2024-01-14 21:24  liessay  阅读(42)  评论(0编辑  收藏  举报