SaveToStream()、LoadFromStream() 对应文本流;
SaveToBinStream()、LoadFromBinStream() 对应二进制流; 相对文本流, 二进制流会小一些.
有这几个方法, 控件数据与状态的序列化就太容易了.
示例:
1、控件: ListBox1、Button1、Button2
2、事件: Button1.OnClick、Button2.OnClick、Form1.OnCreate
unit Unit1; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.Layouts, FMX.ListBox; type TForm1 = class(TForm) ListBox1: TListBox; Button1: TButton; Button2: TButton; procedure FormCreate(Sender: TObject); procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); end; var Form1: TForm1; implementation {$R *.fmx} {给 ListBox1 加点内容} procedure TForm1.FormCreate(Sender: TObject); var i: Integer; begin for i := 0 to 9 do ListBox1.Items.Add('Item' + IntToStr(i)); end; {存取 ListBox1} procedure TForm1.Button1Click(Sender: TObject); const path = 'c: empListBox1Stream.txt'; var stream: TFileStream; begin {1} stream := TFileStream.Create(path, fmCreate); ListBox1.SaveToStream(stream); stream.Free; {2} ListBox1.Clear; ShowMessage('a'); {3} stream := TFileStream.Create(path, fmOpenRead); ListBox1.LoadFromStream(stream); stream.Free; end; {存取当前窗体} procedure TForm1.Button2Click(Sender: TObject); const path = 'c: empForm1Stream.dat'; var stream: TFileStream; begin {1} stream := TFileStream.Create('c: empForm1Stream.dat', fmCreate); Self.SaveToBinStream(stream); stream.Free; {2} Button1.Free; Button2.Free; ListBox1.Free; Realign; ShowMessage('a'); {3} stream := TFileStream.Create('c: empForm1Stream.dat', fmOpenRead); Self.LoadFromBinStream(stream); stream.Free; end; end.
状态保存测试:
1、控件: Button1、Button2、Panel1; 在 Panel1 中再放三个 TCheckBox
2、事件: Button1.OnClick、Button2.OnClick、Form1.OnCreate、Form1.OnDestroy
unit Unit1; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs; type TForm1 = class(TForm) Panel1: TPanel; CheckBox1: TCheckBox; CheckBox2: TCheckBox; CheckBox3: TCheckBox; Button1: TButton; Button2: TButton; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure Button2Click(Sender: TObject); procedure Button1Click(Sender: TObject); end; var Form1: TForm1; implementation {$R *.fmx} var stream: TMemoryStream; procedure TForm1.FormCreate(Sender: TObject); begin stream := TMemoryStream.Create; Button2.Enabled := False; end; procedure TForm1.FormDestroy(Sender: TObject); begin stream.Free; end; {调整三个 CheckBox 的状态后保存} procedure TForm1.Button1Click(Sender: TObject); begin Panel1.SaveToStream(stream); ShowMessage(IntToStr(stream.Size)); Button2.Enabled := True; end; {恢复} procedure TForm1.Button2Click(Sender: TObject); begin stream.Position := 0; Panel1.LoadFromStream(stream); end; end.