ListViewItem 的文本对齐方式

Text Alignment of ListViewItem

在 Delphi 10.4 的 Firemonkey 中。我想构建一个列表视图,其中列表视图项文本显示为左对齐或右对齐,具体取决于列表项内容。

我是这样操作的:

procedure TForm1.FormCreate(Sender: TObject);

  procedure AddItem(No: integer);
  var
    Item: TListViewItem;
  begin
    Item := ListView1.Items.AddItem(No);
    Item.Text := 'Text item No ' + No.ToString;
    Item.Tag := No;
    if No mod 2 = 0 then
      Item.Objects.TextObject.TextAlign := TTextAlign.Leading
    else
      Item.Objects.TextObject.TextAlign := TTextAlign.Trailing;
  end;

var
  c: integer;
begin
  for c := 0 to 9 do
    AddItem(c);
end;

但是,这并不适用于所有平台。但是,一旦 ListView 更改其大小,所有 ListItem 都会在左侧显示为齐平。有更好的方法吗?

作为解决方法,我已执行以下操作:

procedure TForm1.ListView1Resized(Sender: TObject);
var
  c: integer;
begin
  for c := 0 to ListView1.ItemCount - 1  do
    if ListView1.Items[c].Tag mod 2 = 0 then
      ListView1.Items[c].Objects.TextObject.TextAlign := TTextAlign.Leading
    else
      ListView1.Items[c].Objects.TextObject.TextAlign := TTextAlign.Trailing;
end;

使用ItemAppearance=ListItem无法解决这个问题,因为在内部ResetView方法中Item.Objects.TextObject所有属性将写回到ItemAppearanceObjects.ItemObjects

因此,对于此应用程序,ItemAppearance 必须设置为 DynamicAppearance。必须在 ListView.ItemAppearance.Item 下的 结构视图 中手动创建两个 TextObjectAppearance 对象,其中 Text1 必须设置为 TextAlign=LeadingText2TextAlign=Trailing.

之后,只有一个文本对象需要填充文本:

procedure TForm1.FormCreate(Sender: TObject);

  procedure AddItem(No: integer);
  var
    Item: TListViewItem;
  begin
    Item := ListView1.Items.AddItem(No);
    if No mod 2 = 0 then
      Item.Data['Text1'] := 'Text item No ' + No.ToString
    else
      Item.Data['Text2'] := 'Text item No ' + No.ToString
  end;

var
  c: integer;
begin
  for c := 0 to 9 do
    AddItem(c);
end;

对应的FMX文件如下:

object Form1: TForm1
  Left = 0
  Top = 0
  Caption = 'Form1'
  ClientHeight = 480
  ClientWidth = 640
  FormFactor.Width = 320
  FormFactor.Height = 480
  FormFactor.Devices = [Desktop]
  OnCreate = FormCreate
  DesignerMasterStyle = 0
  object ListView1: TListView
    ItemAppearanceClassName = 'TDynamicAppearance'
    ItemEditAppearanceClassName = 'TDynamicAppearance'
    HeaderAppearanceClassName = 'TListHeaderObjects'
    FooterAppearanceClassName = 'TListHeaderObjects'
    Align = Client
    Size.Width = 640.000000000000000000
    Size.Height = 480.000000000000000000
    Size.PlatformDefault = False
    TabOrder = 0
    ItemAppearanceObjects.ItemObjects.ObjectsCollection = <
      item
        AppearanceObjectName = 'Text1'
        AppearanceClassName = 'TTextObjectAppearance'
        Appearance.TextAlign = Leading
      end
      item
        AppearanceObjectName = 'Text2'
        AppearanceClassName = 'TTextObjectAppearance'
        Appearance.TextAlign = Trailing
      end>
    ItemAppearanceObjects.ItemEditObjects.ObjectsCollection = <
      item
        AppearanceObjectName = 'Text1'
        AppearanceClassName = 'TTextObjectAppearance'
      end>
  end
end