我是Xamarin和移动开发的新手,我有winforms和.net的经验,但是线程和MVVM并不是我非常熟悉的。
如果您单击后退,在对话框中选择确定,然后再次单击返回,我的代码将起作用。但我希望通过以下方式改进它:
下面的代码覆盖了android上的后退按钮,如果它返回true。注释掉的部分是我早些时候的饺子。
/// <summary>
/// Gives the user a warning that they are about to close the main page
/// </summary>
public override bool OnAndroidBackButtonPressed()
{
if (this.CloseAppAttempts == 0)
{
try
{
this.device.BeginInvokeOnMainThread(async () =>
{
bool closeApp = await this.DisplayService.DisplayAlertAsync("Close app", "Click the OK button to close the app / or click the back button again to close the app", "Ok", "Cancel");
if (closeApp)
{
// this.DisplayService.CloseAsync();
// this.DisplayService.ExitAsync();
// this.DisplayService.pageStack.Pop();
// await IDisplayService.navigation.PopAsync();
this.CloseAppAttempts++;
// i would like to either call the backbutton programatically here, or close
}
});
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("===== Debug Message - Closing the app did not work - [ " + ex.Message + " ]");
}
return true;
}
else
{
return false;
}
}
以下代码覆盖后退按钮并在返回之前警告用户:
public class MainActivity : Activity
{
. . .
bool pressed = false;
public override void OnBackPressed()
{
if (!pressed)
{
Toast.Show("Press again to exit"); //Implement the Toast correctly
pressed = true;
}
else
base.OnBackPressed();
}
}
(添加一些逻辑来重新装配这个Toast,所以如果用户在一段时间后按下按钮,它会再次显示)
下一个片段显示一条消息(我不知道如何在Xamarin.Android中显示消息,但逻辑是存在的)
public class MainActivity : Activity
{
. . .
public override void OnBackPressed()
{
if (Alert("Exit?", "Yes", "No"))
base.OnBackPressed();
}
}
在Xamarin.Forms上,您需要知道正在显示的页面,因此您不会在每个页面和子页面上显示该对话框。
在这种情况下,我使用NavigationPage来控制所有页面。
public class MainActivity : global::Xamarin.Forms.P . . .
{
. . .
bool pressed = false;
public override void OnBackPressed()
{
if (Xamarin.Forms.Application.Current.MainPage.Navigation.NavigationStack.Count == 1)
{
if (Xamarin.Forms.Application.Current.MainPage.Navigation.NavigationStack[0].DisplayAlert(
"Confirm exit",
"Do you really want to exit?",
"Yes", "No"))
base.OnBackPressed();
}
else
base.OnBackPressed();
}
}
您可以使用以下命令关闭android上的应用程序:
public void CloseApplication()
{
var activity = (Activity)Forms.Context;
activity.FinishAffinity();
}
使用Xamarin.Forms,您可以通过依赖服务调用它。