3

I have created a Toolbar for an activity in Android in Xamarin. I have enabled the back/home button with SupportActionBar.SetDisplayHomeAsUpEnabled(true);. I am trying to capture the event of pressing the back/home button with the following code, as instructed by this and many other stackoverflow posts:

public override bool OnOptionsItemSelected(IMenuItem item)
        {
            System.Diagnostics.Debug.WriteLine("OnOptionsItemSelected() called: " + item.ItemId);
            switch (item.ItemId)
            {
                case Resource.Id.home:
                    System.Diagnostics.Debug.WriteLine("Home button pressed");
                    Finish();
                    return base.OnOptionsItemSelected(item);
                default:
                    return base.OnOptionsItemSelected(item);
            }
        }

When I press the back button, OnOptionsItemSelected is called, but item.ItemId is not equal to Resource.Id.home. The former is 16908332 (tested on two different devices) but the latter is 2131492903. How can I capture the home/back button from the toolbar in Xamarin? One possible option is to hardcode the back button ID as 16908332, but I do not know if that number will stay the same permanently.

SushiHangover
  • 73,120
  • 10
  • 106
  • 165
Alex Fischer
  • 545
  • 3
  • 11
  • 1
    You want the system resource ID, not one from your app. In Xamarin, I believe it's [`Android.Resource.Id.Home`](https://developer.xamarin.com/api/field/Android.Resource+Id.Home/). – Mike M. Jul 19 '18 at 14:41

2 Answers2

4

You are using the wrong resource, you want the one from the Android space:

Android.Resource.Id.Home
SushiHangover
  • 73,120
  • 10
  • 106
  • 165
  • Out of curiosity what's the Resource.Id.Home for? To confuse people and have them spend hours searching until they find this? :)) – asnyder Nov 09 '18 at 15:01
  • @asnyder Using Resource.Id.home (technically `R.Id.home`) in theory you can build your own navigation stack and thus define your own "home", personally I have never seen it done and not really sure how it would apply to an app (maybe defining a launcher that uses a stacked navigation for drilling down and back, .... ?) – SushiHangover Nov 09 '18 at 15:11
0

The right one to use is

case Android.Resource.Id.Home:
                Finish();
                break;
VSB
  • 317
  • 2
  • 10