為了顯示一個網頁,我做了一個窗口,同樣參考前面寫過的為Android做一個ShowModal窗口。先看一下代碼:
unit Form.WebBrowser; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, System.Threading, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Objects, FMX.Layouts, CC.NavigationBar, CC.StatusBar, CC.X5WebView, FMX.WebBrowser; type TWebBrowserForm = class(TForm) CCStatusBar1: TCCStatusBar; CCNavigationBar1: TCCNavigationBar; Rectangle1: TRectangle; WebBrowser1: TWebBrowser; CCX5WebView1: TCCX5WebView; procedure FormCreate(Sender: TObject); procedure FormKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState); private FURL: string; procedure SetURL(const Value: string); public property URL:string read FURL write SetURL; end; procedure ShowWebBrowserForm(const AURL:string; AFormResult: TProc<TModalResult>=nil); implementation {$R *.fmx} //調用方法: // ShowWebBrowserForm('https://www.baidu.com/', // procedure(AResult: TModalResult) // begin // // end); var WebBrowserForm: TWebBrowserForm; procedure ShowWebBrowserForm(const AURL:string; AFormResult: TProc<TModalResult>); begin if not assigned(WebBrowserForm) then begin WebBrowserForm := TWebBrowserForm.Create(Application); end; WebBrowserForm.URL:=AURL; WebBrowserForm.ShowModal( procedure(AResult: TModalResult) begin if Assigned(AFormResult) then AFormResult(AResult); TTask.Run( procedure begin TThread.Synchronize(nil, procedure begin WebBrowserForm.DisposeOf; WebBrowserForm := nil; end); end); end); end; procedure TWebBrowserForm.FormCreate(Sender: TObject); begin {$IFDEF ANDROID} WebBrowser1.Free; {$ELSE} CCX5WebView1.Free; {$ENDIF} end; procedure TWebBrowserForm.FormKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState); begin if Key = vkHardwareBack then self.ModalResult := mrCancel; end; procedure TWebBrowserForm.SetURL(const Value: string); begin FURL := Value; {$IFDEF ANDROID} CCX5WebView1.loadURL(Value); {$ELSE} WebBrowser1.Navigate(Value); {$ENDIF} end; end.
通過代碼,可以看到:
1.使用了ChinaCock的X5WebView來支持android
2.使用了原生的WebBrowser來支持Windows平台,因為ChinaCock的X5WebView現在不支持Windows平台。這里有個小坑,我在運行期建立WebBrowser實例,發現不顯示網頁,設計期放置到Form上,就正常,這應該是10.4.2的bug.
3.調用方法在注釋中寫了,可以使用回調函數,也可以省略,只顯示一個網頁。
4.最后,開發環境:在10.4.2下測試通過
你要是使用,建一個Form,放置一個X5WebView及WebBrowser兩個組件即可,然后復制這里的代碼。好象再沒有什么可寫的了。