简体   繁体   中英

How to avoid OnCreate method execution when activity has been opened previously (Xamarin.Android)?

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 ?

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.

在此处输入图片说明

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM