Xamarin.Android , OnBackPressed() 方法处理

Xamarin.Android , OnBackPressed() method handling

我有 main_activity 和 dashboard_activity,在 dashboard_activity 我使用 OnBackPressed() 方法中的代码添加了片段

public override  void OnBackPressed()
    {
         //base.OnBackPressed();
             FragmentTransaction transaction =FragmentManager.BeginTransaction();
             Dialog dialog = new Dialog();
             dialog.Show(transaction,"dialog_fragment");
    }

我的片段代码在这里

class Dialog:DialogFragment
{
    private Button btnExitapp;
    private Button btnLogOut;

    public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
         base.OnCreateView(inflater, container, savedInstanceState);
        var view = inflater.Inflate(Resource.Layout.dialog, container,false);

        btnExitapp=view.FindViewById<Button>(Resource.Id.btnExitapp);
        btnExitapp.Click += BtnExitapp_Click;

        btnLogOut = view.FindViewById<Button>(Resource.Id.btnLogOut);
        btnLogOut.Click += BtnLogOut_Click;

        return view;
    }
    
    private void BtnLogOut1_Click(object sender, EventArgs e)
    {
        
        
    }

    private void BtnExitapp1_Click(object sender, EventArgs e)
    {
        System.Diagnostics.Process.GetCurrentProcess().Kill();
    }
    
}

注意:我的 btnExitapp 代码在部署后只能正常工作一次,如果我在模拟器中重新打开应用程序并按 btnExit,它会关闭应用程序并使用 Dashboard_Activity 重新打开而不是关闭应用程序。

请指导我实现 当按下 BtnLogout 时,应该返回 Main_Activity,因为它在后按按钮上工作,当按下 BtnExitapp 时应该关闭应用程序

首先,如果你想在你的对话中回到之前的activity,你可以尝试调用private void BtnLogOut1_Click(object sender, EventArgs e)中的base.OnBackPressed();。此外,也许你需要调用它两次,从对话框到 dashborad activity 然后是主要的 activity.

然后如果你想退出应用程序,你可以使用下面的代码:

private void BtnExitapp1_Click(object sender, EventArgs e)
{
   Android.OS.Process.KillProcess(Android.OS.Process.MyPid());
}