0

I have two activities FirstActivity and SecondActivity. When I am in FirstActivty I call the SecondActivity like that:

var secondActivity = new Intent(this, typeof(SecondActivity));
secondActivity.PutExtra("someExtra", someExtra);
StartActivity(secondActivity);
Finish();

In SecondActivity I call the FirstActivity in OnBackPressed method:

public override void OnBackPressed()
{
    StartActivity(typeof(FirstActivty));
    Finish();
}

I looked at answers regarding that question for Android(Java). The answers were that in order to avoid OnCreate method to be executed in FirstActivity when the activity has been already created, I don't have to destroy FirstActivity after I open SecondActivity, I have to remove Finish() after StartActivity(secondActivity); line. I removed it but OnCreate method still gets executed when I go back from SecondActivity. Does this solution work only in Android(Java) ,and if yes, what is the solution for Xamarin.Android ?

4

1 回答 1

1

You can add LaunchMode = Android.Content.PM.LaunchMode.SingleInstance in your FirstActivity attribute like this code.

   [Activity(Label = "@string/app_name", Theme = "@style/AppTheme", MainLauncher = true,LaunchMode = Android.Content.PM.LaunchMode.SingleInstance)]
    public class MainActivity : AppCompatActivity
    {
        
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            Xamarin.Essentials.Platform.Init(this, savedInstanceState);
            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.activity_main);
           
        }

Here is running GIF.

enter image description here

If you do not want to execute the code in the Oncreate method, You can refer to this thread. https://stackoverflow.com/a/6931246/10627299

于 2020-03-25T06:29:02.953 回答