How to navigate between views via button clicks with a single activity in Xamarin.Android?

Viewed 338

In Xamarin Android (NOT Xamarin.Forms), I have 2 views, each with a button.

In MainActivity.cs, I start out with the first view and set an onClick handler for the first button. Clicking that button opens the second view, which is working correctly.

Also in MainActivity.cs, I set an onClick handler for the second button (in the second view). However, clicking that button does nothing -- I even set a breakpoint in the handler but it never fires. I want to add some logic but for now all I want is to navigate back to the first view. Here is the code for setting the handler for the second button...

View v2 = this.LayoutInflater.Inflate(Resource.Layout.view2, null);
Button b2 = v2.FindViewById<Button>(Resource.Id.button2);
b2.Click += b2OnClick;

...and the click handler...

private void b2OnClick(object sender, EventArgs eventArgs)
{
    SetContentView(Resource.Layout.view1);
}

I would like to use only MainActivity.cs but if that is not possible, please provide an alternate solution.

1 Answers

The view2 you instantiate at first is not the view you set after , so the button click would never trigger, you should create a global variable for that two views , for example

    View v1,v2;
    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
        Xamarin.Essentials.Platform.Init(this, savedInstanceState);

        v1 = this.LayoutInflater.Inflate(Resource.Layout.content_main, null);
        Button button = v1.FindViewById<Button>(Resource.Id.button1);
        button.Click += Button_Click;


        v2 = this.LayoutInflater.Inflate(Resource.Layout.XMLFile1, null);
        Button button2 = v2.FindViewById<Button>(Resource.Id.button2);
        button2.Click += Button2_Click;

        SetContentView(v1);

    }


    private void Button_Click(object sender, EventArgs e)
    {
        SetContentView(v2);
    }

    private void Button2_Click(object sender, EventArgs e)
    {
        SetContentView(v1);
    }
Related