在自定义Popup内容视图中,监听hardwareBack即可解决这个问题。
public class CustomPopup : PopupPage
{
public CustomPopup ()
{
//...
this.BackgroundColor = Color.FromRgba (0, 0, 0, 0.5);
}
protected override bool OnBackgroundClicked ()
{
return false; // Disable background click dismiss
}
protected override bool OnBackButtonPressed ()
{
return false; // Disable the hardware back button
}
protected override void OnAppearing ()
{
base.OnAppearing ();
// Listen hardware back button press
Xamarin.Forms.Device.StartTimer (TimeSpan.FromSeconds (0.5), () =>
{
if (Xamarin.Forms.Device.RuntimePlatform == Device.Android && Xamarin.Forms.Application.Current.MainPage == this)
{
Device.StartTimer (TimeSpan.FromMilliseconds (200), () =>
{
base.OnBackButtonPressed(); // Manually raise back button event
return false; // Done
});
}
return false; // Done
});
}
protected override void OnDisappearing ()
{
base.OnDisappearing ();
}
}
然后,您可以像这样实例化并显示Popup:
CustomPopup popup = new CustomPopup ();
await popup.ShowAsync ();
这样,当用户点击硬件“返回”按钮时,弹出窗口将自动关闭。