Delphi XE8 Firemonkey TListView - How to set a background color programmatically

3.8k Views Asked by At

A TListView is connected with a style. This style contains a TColorObject named background. If you set the TColorObject.Color (red) in the styledesigner the Treeview will show this Color. If the Color is set programmatically in the ApplyStyleLookup Event of TListView the background Color remains on the Color (red) set in the style!!!!

procedure TTest.TreeViewlistApplyStyleLookup(Sender: TObject);
var
 co: TColorObject;
begin
co := nil;
if Sender is TListView then  co := TListView(Sender).FindStyleResource('background') as TColorObject;
if co <> nil then co.Color := TAlphaColors.Black;    
//co is not nil 
//TColorObject background is found and black is set, but it remains on red
end;
3

There are 3 best solutions below

1
On

You can put TListView inside on TRectangle, and set Transparent property of listview in True.

1
On

You could add in a helper to set the private variable in the TCustomListView
although for some reason it only works after you have added some items in

unit ListViewHelper;

interface
uses  FMX.ListView, System.UITypes ;
type
  TListViewHelper = class helper for TCustomListView
    procedure SetItemStyleFillColour(Colour : TAlphaColor);
    procedure SetBackgroundStyleColor(Colour : TAlphaColor);
  end;

implementation

{ TListViewHelper }

procedure TListViewHelper.SetBackgroundStyleColor(Colour: TAlphaColor);
begin
  TCustomListView(self).FBackgroundStyleColor := Colour;
end;

procedure TListViewHelper.SetItemStyleFillColour(Colour: TAlphaColor);
begin
  TCustomListView(self).FItemStyleFillColor := Colour;
end;

end.

then use that unit wherever you want to change the background colour and call the SetItemStyleFillColour

lv1.SetItemStyleFillColour(TAlphaColor($FF4A494A));
lv1.SetBackgroundStyleColor( TAlphaColorRec.Blue);

e.g.

unit Main;

interface

uses
  System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
  FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs,
  FMX.ListView.Types, FMX.ListView;

type

  TForm1 = class(TForm)
    lv1: TListView;
    procedure FormCreate(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation
uses ListViewHelper;

{$R *.fmx}

procedure TForm1.FormCreate(Sender: TObject);
begin
  lv1.Items.Add.Text := FormatDateTime('dd-mm-yyyy HH:NN:SS ZZZ', Now());
  lv1.Items.Add.Text := FormatDateTime('dd-mm-yyyy HH:NN:SS ZZZ', Now());
  lv1.SetItemStyleFillColour(TAlphaColor($FF4A494A));
  lv1.SetBackgroundStyleColor( TAlphaColorRec.Blue);
end;

end.
1
On
use System.Rtti; 

TRttiContext.Create.GetType(TListView).GetField('FBackgroundStyleColor').SetValue(ListView2, TAlphaColorRec.Orange);

TRttiContext.Create.GetType(TListView).GetField('FItemStyleFillColor').SetValue(ListView2, TAlphaColorRec.Azure);