Returning to previous activity in Xamarin Android

本秂侑毒 提交于 2021-02-11 15:02:59

问题


I have two activities: MainActivity and Activity2:

public class MainActivity : AppCompatActivity
{
    DateTime time = DateTime.Now;        
    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
        Xamarin.Essentials.Platform.Init(this, savedInstanceState);
        SetContentView(Resource.Layout.activity_main);

        var button = FindViewById<Button>(Resource.Id.button);
        button.Text = "Button created at " + time.ToString();
        button.Click += (s, e) =>
        {
            Intent intent = new Intent(this, typeof(Activity2));
            StartActivity(intent);
        };
    }
    public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
    {
        Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);
        base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
    }
}

and:

[Activity(Label = "Activity2")]
public class Activity2 : Activity
{
    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
        SetContentView(Resource.Layout.activity2);

        Button button_close = FindViewById<Button>(Resource.Id.button_close);
       
        button_close.Click += (s, e) =>
        {
            Intent intent = new Intent(this, typeof(MainActivity));
            StartActivity(intent);
        };
    }
}

Clicking on button opens Activity2 and hides MainActivity. button_close closes Activity2 and opens a new instance of MainActivity. But I do not want a new instance to be created. How can I revive exactly the original previously-created instance of MainActivity and return to it after Activity2 is closed?

Here, button.Text shows whether a new instance of MainActivity is created.


回答1:


Just call Finish() on Activity2, it will return to the previous.

If you want to pass some kind of result, you can use StartActivityForResult and in OnActivityResult get the resulting data.



来源:https://stackoverflow.com/questions/64781608/returning-to-previous-activity-in-xamarin-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!