如何处理(Delphi)Android应用程序中的后退按钮?

Wou*_*ick 15 delphi android back-button delphi-xe5

如何让我的Android应用程序对后退按钮作出反应?

有没有什么东西可以作为高级VCL的TApplicationEvents来处理它,或者我是否需要深入研究低级Android特定的东西?

现在,大多数演示应用程序都有一个屏幕后退按钮,可以返回上一个屏幕.按下psysical按钮似乎总是退出应用程序,在某些情况下会导致访问冲突.

Rem*_*eau 34

在表单的OnKey...事件中,Key参数vkHardwareBack在Android上.例如:

uses
  FMX.Platform, FMX.VirtualKeyboard;

procedure TForm1.FormKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState);
var
  FService : IFMXVirtualKeyboardService;
begin
  if Key = vkHardwareBack then
  begin
    TPlatformServices.Current.SupportsPlatformService(IFMXVirtualKeyboardService, IInterface(FService));
    if (FService <> nil) and (vksVisible in FService.VirtualKeyBoardState) then
    begin
      // Back button pressed, keyboard visible, so do nothing...
    end else
    begin
      // Back button pressed, keyboard not visible or not supported on this platform, lets exit the app...
      if MessageDlg('Exit Application?', TMsgDlgType.mtConfirmation, [TMsgDlgBtn.mbOK, TMsgDlgBtn.mbCancel], -1) = mrOK then
      begin
        // Exit application here...
      end else
      begin
        // They changed their mind, so ignore the Back button press...
        Key := 0;
      end;
    end;
  end
  ...
end;
Run Code Online (Sandbox Code Playgroud)

  • 在XE6及更高版本中,`vksVisible`被替换为[TVirtualKeyboardState.Visible](http://docwiki.embarcadero.com/Libraries/en/FMX.Types.TVirtualKeyBoardState). (6认同)

Ser*_*kov 6

这是Remy答案的更新代码(适用于西雅图):

procedure TForm1.FormKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState);
var
  FService : IFMXVirtualKeyboardService;
begin
  if Key = vkHardwareBack then
  begin
    TPlatformServices.Current.SupportsPlatformService(IFMXVirtualKeyboardService, IInterface(FService));
    if (FService <> nil) and (TVirtualKeyboardState.Visible in FService.VirtualKeyBoardState) then
    begin
      // Back button pressed, keyboard visible, so do nothing...
    end else
    begin
      Key := 0;
      // Back button pressed, keyboard not visible or not supported on this platform, lets exit the app...
      MessageDlg('Exit Application?', TMsgDlgType.mtConfirmation, [TMsgDlgBtn.mbOK, TMsgDlgBtn.mbCancel], -1, OnCloseDialog);
    end;
  end;
end;

procedure TForm1.OnCloseDialog(Sender: TObject; const AResult: TModalResult);
begin
  if AResult = mrOK then
    Close;
end;
Run Code Online (Sandbox Code Playgroud)


小智 6

为了将来参考任何试图弄清楚这一点的人.

if Key = vkHardwareBack then
    begin
      // your code here
      key := 0;
end;
Run Code Online (Sandbox Code Playgroud)

关键:= 0; 是阻止应用关闭的秘诀..

这是OnKeyUp事件的形式