[英]How to extract original JString value from Listbox in Android Kitkat Delphi XE8
我正在用Delphi xe8做一個測試android多設備應用程序。 我將對象附加到列表框中的項目,如下所示:
unit Unit1;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes,
System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics,
Androidapi.JNI.JavaTypes, FMX.Dialogs,
FMX.Controls.Presentation, FMX.StdCtrls, FMX.Layouts, FMX.ListBox,
Androidapi.Helpers;
type
TForm1 = class(TForm)
ListBox1: TListBox;
Button1: TButton;
Button2: TButton;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.fmx}
//this where I am Attaching objects to items
procedure TForm1.Button1Click(Sender: TObject);
var
str:string;
jstr1:JString;
begin
str:='apple';
jstr1:=StringToJString(str);
ListBox1.Items.AddObject('fruit', TObject(jstr1));
end;
//this where I am extracting the jstring objects
procedure TForm1.Button2Click(Sender: TObject);
var
jstr2:JString;
str2:string;
begin
jstr2:=JString(ListBox1.Items.Objects[i]);
str2:=JStringToString(jstr2);
showmessage('the fruit of the day is '+str2);
end;
end.
上面的代碼運行正常,並且jstring對象已附加到項目中,但是,當我要提取已附加到該項目的jstring對象時,我會這樣做:
jstr2:=JString(ListBox1.Items.Objects[i]);
//Above give me an AV: I get incompatible types TObject and JString
str2:=JStringToString(jstr2);
上面的代碼由於類型不兼容的TObject和JString而無法編譯。 但是,如果將字符串作為對象(而不是jstring)附加並想要取回那些字符串對象,我可以這樣做:
str2:=String(ListBox1.Items.Objects[i]);
這將與常規字符串一起使用。 如何解決此問題,附加並提取jstring?
這只是一個建議,我無法檢查(此處未安裝任何東西),但是您可以編寫一個簡單的對象類型並將其存儲(我將其放在自己的單元中,然后在表單單元中使用):
unit StringObjs;
interface
uses
Androidapi.JNI.JavaTypes;
type
TStringObj = class
private
FPayload: string;
public
constructor Create(const Payload: JString);
class operator Explicit(const Obj: TStringObj): string;
end;
implementation
uses
Androidapi.Helpers;
constructor TStringObj.Create(const Payload: JString);
begin
FPayload := JStringToString(Payload); // store string, not JString!
end;
class operator TStringObj.Explicit(const Obj: TStringObj): string;
begin
Result := Obj.FPlayload;
end;
end.
然后在表單單元的實現部分中使用它,例如:
implementation
uses ..., StringObjs;
...
ListBox1.Items.AddObject('fruit', TStringObj.Create(jstr1));
並反向:
MyString := string(ListBox1.Items[0] as TStringObj);
請注意,表單只是一類,但是IDE知道並且可以使用表單設計器進行編輯。 要聲明其他類,請執行與上面類似的操作。 閱讀《 Delphi語言指南》以了解更多信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.