Search code examples
xamarin.android

Xamarin.Android , OnBackPressed() method handling


I have main_activity and dashboard_activity, on dashboard_activity I added fragment using code in OnBackPressed() method

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

My fragment code is here

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();
    }
    
}

Note:My code for btnExitapp work fine only once after deployment and if I reopen the app in emulator and press btnExit it close app and reopen with Dashboard_Activity instead of closing app.

Please guide me to achieve that when BtnLogout pressed, should go back to Main_Activity as it work on backpress button and when BtnExitapp pressed should close the app


Solution

  • At first, if you want to go back to the previous activity in your dialogframent, you can try to call the base.OnBackPressed(); in the private void BtnLogOut1_Click(object sender, EventArgs e). In addition, maybe you need to call it twice, from dialog to dashborad activity and then the main activity.

    Then if you want to exit the app, you can use the following code:

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