1. 程式人生 > 其它 >為app建立一個瀏覽器視窗

為app建立一個瀏覽器視窗

為了顯示一個網頁,我做了一個視窗,同樣參考前面寫過的為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兩個元件即可,然後複製這裡的程式碼。好象再沒有什麼可寫的了。