我在这个领域是新手,遇到这样的情况,我有两页内容:
MainActivity.axml
SecondActivity.axml
我在MainActivity中有一个名为BtnOther的按钮,在此按钮中,我想导航到SecondActivity。在SecondActivity中,我有btnBackToExisting1stPage按钮,我想回到MainActivity。通常它可以,但是:
单击BtnOther或android后退箭头后,应用程序将在模拟器上最小化并且不会停留在前面。为什么会这样,以及如何避免呢?
我想按BtnOther或向后箭头以从SecondActivity返回MainActivity BUT来像以前一样打开确切的MainActivity状态。例如,如果我在MainActivity上具有文本编辑字段,然后在进入SecondActivity之前放一些文本,然后从SecondActivity返回时,我想看到MainActivity的表单状态完全相同,而不是像在当前代码中那样创建新的状态。 / p>
我当前的代码:
public class MainActivity : AppCompatActivity
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
Plugin.CurrentActivity.CrossCurrentActivity.Current.Init(this, savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.activity_main);
var btnOther = FindViewById<Button>(Resource.Id.Other);
btnOther.Click += BtnOther_Click;
}
private void BtnOther_Click(object sender, EventArgs e)
{
Intent nextActivity = new Intent(this, typeof(SecondActivity));
StartActivity(nextActivity);
Finish();
}
}
public class SecondActivity : Activity
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Create your application here
SetContentView(Resource.Layout.Second);
var btnBackToExisting1stPage = FindViewById<Button>(Resource.Id.BackToExisting1stPage);
btnBackToExisting1stPage.Click += OnBackPressed;
}
private void OnBackPressed(object sender, EventArgs e)
{
OnBackPressed();
}
public override void OnBackPressed()
{
Toast.MakeText(this, "Back button Pressed", ToastLength.Short).Show();
base.OnBackPressed();
Finish();
}
}
答案 0 :(得分:2)
从单击按钮开始第二个活动时,您正在调用“ finish()”,这会破坏MainActivity并创建SecondActivity。只需删除/注释“ finish()”调用即可。即使单击后退按钮,您也将拥有MainActivity中保留的实例。