Giải pháp được đề xuất có thể hoạt động tốt, nhưng tôi không thích "phơi nhiễm thuộc tính tĩnh" để giải quyết các vấn đề. Hơn nữa, tôi không thích việc sử dụng các giải pháp "các thuộc tính như các phương thức", đặc biệt khi có rất nhiều logic liên quan.
Vấn đề chính ở đây là cách chúng tôi có thể xử lý phương thức OnBackButton() từ lớp Xamarin.Forms.Application của chúng tôi.
Điều gì sẽ làm tương tự một cách thanh lịch hơn?
Trước tiên, bạn cần mở rộng Xamarin.Forms.Lớp ứng dụng như sau:
namespace YourNameSpace
{
public class Application : Xamarin.Forms.Application
{
#region Public Methods
public bool HandleBackButton()
{
return OnBackPressed();
}
#endregion
#region Application Methods
protected virtual bool OnBackPressed()
{
return false;
}
#endregion
}
}
Triển khai ứng dụng của bạn bây giờ sẽ sử dụng lớp này làm lớp cơ sở. Hãy nhớ sửa đổi xaml và xaml.cs của bạn cho phù hợp:
<common:Application xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:common="clr-namespace:YourNameSpace"
x:Class="YourNameSpace.App">
</common:Application>
Trong triển khai App.cs của bạn, bạn có thể ghi đè phương pháp OnBackButton().
public partial class App : YourNameSpace.Application
{
#region Constructors
public App()
{
InitializeComponent();
}
#endregion
#region App Methods
protected override bool OnBackPressed()
{
// Handle when the back button is pressed
return false;
}
#endregion
}
Sau đó, bạn cần thay đổi một chút việc triển khai lớp Hoạt động của mình.
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
#region Constants and Fields
private App _app;
#endregion
#region Activity Methods
protected override void OnCreate(Bundle bundle)
{
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
base.OnCreate(bundle);
global::Xamarin.Forms.Forms.Init(this, bundle);
_app = new App();
LoadApplication(_app);
}
public override void OnBackPressed()
{
if(!_app.HandleBackButton())
base.OnBackPressed();
}
#endregion
}
Điều này sẽ không hoạt động, bởi vì tôi đang sử dụng biểu mẫu xamarin, để tôi chỉ có một hoạt động – Chris