Search code examples
android-activitytypesxamarin.androidparameter-passing

How to pass Activity type to a method in Xamarin.Android?


All my activities inherit from BaseActivity. In BaseActivity I have the following method:

protected void GoToPreviousActivity(Activity)
{
    StartActivity(typeof(Activity));
    Finish();
}

When I click the toolbar's back button of every activity I want to go back to the previous activity, like that:

toolbar.NavigationOnClick += delegate
{
    this.GoToPreviousActivity(PreviousActivity);
};

How can I do that?


Solution

  • As @Mathias Kirkegaard commented, Android provides its own navigation back and it is very reliable (you can even manipulate the back stack (see the link at the bottom about what is it))

    Having said that, if you want to use your method every time the user clicks on the back button you can override the OnBackPressed method, and provide your own implementation there. In your case:

     public override void OnBackPressed()
        {
            //base.OnBackPressed(); <-- this will use the default behaviour to navigate back, and if I understood correctly, you don't want to use it
            GoToPreviousActivity(PreviousActivity);
        }
    

    Even though you can do that and it is valid, it is discouraged, you can read more about how Android manages the back navigation here: https://developer.android.com/guide/components/activities/tasks-and-back-stack

    and here is a good article on how to implement a custom back navigation: https://developer.android.com/guide/navigation/navigation-custom-back