Orion
Orion

Reputation: 1276

How to navigate back/up using Xamarin and MVVMCross

I'm asking this question to create a record of this for myself, I found out the answer by looking around but I feel like it took me way too long to figure this out. Assuming I was using the wrong keywords in my searches I am trying to link the keywords I used in my searches to this question and hopefully help someone else.

I was trying to navigate back to the previous activity using the OnOptionsItemSelected method. This is how Android allows you to listen to actionbar button presses.

public override bool OnOptionsItemSelected(IMenuItem item)
{
    if (item.ItemId != global::Android.Resource.Id.Home) return base.OnOptionsItemSelected(item);

    ViewModel.BackNavigationButtonCommand.Execute();
    return true;
}

I was enabling the back button by using:

SupportActionBar.SetHomeButtonEnabled(true);
SupportActionBar.SetDisplayHomeAsUpEnabled(true);

The SetDisplayHomeAsUpEnabled callback however did not go to OnOptionsItemSelected.

Upvotes: 1

Views: 194

Answers (1)

Orion
Orion

Reputation: 1276

The answer to this solution is using the activity attribute:

[Activity(
    Label = "Project Wavelength"
    , Icon = "@drawable/icon"
    , Theme = "@style/Theme.AppCompat.Light.DarkActionBar"
    , ScreenOrientation = ScreenOrientation.Portrait
    , LaunchMode = LaunchMode.SingleTop)]

LaunchMode = LaunchMode.SingleTop for returning to an existing activity in the backstack.

[Activity(Label = "DevicesWithSensorsForRoom"
    , Icon = "@drawable/icon"
    , ScreenOrientation = ScreenOrientation.Portrait
    , Theme = "@style/Theme.AppCompat.Light.DarkActionBar"
    , ParentActivity = typeof(RoomsOverviewActivity)
    , LaunchMode = LaunchMode.SingleTop)]

ParentActivity = typeof(RoomsOverviewActivity) for defining the parent to return to.

I don't know if there is an MVVMCross solution to this using the viewmodels. This however works for me right now. If there is a MVVMCross solution I'd like to hear it.

The OnOptionsItemSelected and SetDisplayHomeAsUpEnabled are not necessary with these attributes.

Upvotes: 1

Related Questions