FMX.TListView (C++) - Sorting
Description
This example shows how to implement a sort function for FMX TListView items.
To test this example, create a new FireMonkey application and add a Delphi source unit to the C++ project to instantiate the generic class:
unit ImportUnitToInclude;
interface
uses
System.Generics.Defaults,
FMX.ListView.Appearances;
implementation
//force the generic/template to be generated by the Delphi compiler
var
Comparer : TComparer<TListViewItem>;
end.
Delphi generics need to have an instantiation available in order for C++ to use them.
When using the Clang compiler, you can use use a lambda expression or a functor. The following code uses a lambda expression:
void SortListViewClangOnly(TListView *ListViewToSort)
{
//using lambda expression for sorting
ListViewToSort->Items->Sort(TComparer__1<TListViewItem*>::Construct([](TListViewItem* Left, TListViewItem* Right) -> int
{
return CompareText(Left->Text, Right->Text);
} ));
}
If you are using a classic compiler, only the functor expression can be used:
void SortListViewClangAndClassic(TListView *ListViewToSort)
{
//using a functor for sorting
typedef TComparison__1<TListViewItem*> TCompLVItem;
struct TFmxLVSortCompare : public TCppInterfacedObject< TCompLVItem>
{
virtual int __fastcall Invoke(TListViewItem* Left, TListViewItem* Right)
{
return CompareText(Left->Text, Right->Text);
};
};
ListViewToSort->Items->Sort(TComparer__1<TListViewItem*>::Construct(new TFmxLVSortCompare()));
}
To call one of the previous implementations, you can use the following code:
void __fastcall TForm2::Button4Click(TObject *Sender)
{
SortListViewClangAndClassic(ListView1);
}
Or
void __fastcall TForm2::Button1Click(TObject *Sender)
{
#ifdef __clang__
SortListViewClangOnly(ListView1);
#else
ShowMessage(L"This is only for clang");
#endif
}