[英]How to avoid OnCreate method execution when activity has been opened previously (Xamarin.Android)?
I have two activities FirstActivity
and SecondActivity
.我有两个活动FirstActivity
和SecondActivity
。 When I am in FirstActivty
I call the SecondActivity
like that:当我在FirstActivty
时,我像这样调用SecondActivity
:
var secondActivity = new Intent(this, typeof(SecondActivity));
secondActivity.PutExtra("someExtra", someExtra);
StartActivity(secondActivity);
Finish();
In SecondActivity
I call the FirstActivity
in OnBackPressed
method:在SecondActivity
我所说的FirstActivity
在OnBackPressed
方法:
public override void OnBackPressed()
{
StartActivity(typeof(FirstActivty));
Finish();
}
I looked at answers regarding that question for Android(Java)
.我查看了有关该问题的答案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);
答案是,为了避免OnCreate
中要执行的方法FirstActivity
活动已经被创建的时候,我没有破坏FirstActivity
后,我打开SecondActivity
,我不得不删除Finish()
后StartActivity(secondActivity);
line.线。 I removed it but OnCreate
method still gets executed when I go back from SecondActivity
.我删除了它,但是当我从SecondActivity
返回时, OnCreate
方法仍然被执行。 Does this solution work only in Android(Java)
,and if yes, what is the solution for Xamarin.Android
?此解决方案是否仅适用于Android(Java)
,如果是, Xamarin.Android
的解决方案是什么?
You can add LaunchMode = Android.Content.PM.LaunchMode.SingleInstance
in your FirstActivity
attribute like this code.您可以像此代码一样在FirstActivity
属性中添加LaunchMode = Android.Content.PM.LaunchMode.SingleInstance
。
[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.这里正在运行 GIF。
If you do not want to execute the code in the Oncreate
method, You can refer to this thread.如果不想执行Oncreate
方法中的代码,可以参考这个线程。 https://stackoverflow.com/a/6931246/10627299 https://stackoverflow.com/a/6931246/10627299
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.