在您的“启动屏幕活动”上,您可以设置活动的NoHistory = true,假设您不想重新显示应用程序的启动屏幕。
您可以对登录活动执行相同的操作,但如果用户未登录,您可能希望返回登录活动,因此在您的“家庭活动”中覆盖OnBackPressed():
示例:
public override void OnBackPressed()
{
if (YourUsersLoginStatus = false)
{
base.Onbackpressed
// Finish this activity unless you need to keep it for some reason
finish();
} else {
// Do nothing as you want to stay on this activity as your
// User is still logged in
}
}
NoHistory 属性:
Android 风格:
[android:noHistory="true"] attribute
Xamarin 风格:
[Activity (NoHistory = true)]
Android.App.ActivityAttribute.NoHistory 属性
是否应该从活动堆栈中删除活动
并在用户离开时完成。
语法
public Boolean NoHistory { get;放; }
Value : 一个布尔值,指定活动是否应该
从活动堆栈中删除并在用户导航时完成
离开。
参考:http://developer.xamarin.com/api/property/Android.App.ActivityAttribute.NoHistory/
参考:http://developer.xamarin.com/guides/android/application_fundamentals/activity_lifecycle/
参考:http://developer.android.com/reference/android/R.styleable.html#AndroidManifestActivity_noHistory
更新:
NoHistory 属性设置为 true 且 MainLauncher 设置为 true 的启动屏幕活动
[Activity(Theme = "@style/Theme.Splash", MainLauncher = true, NoHistory = true)]
public class SplashActivity : Activity
{
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
StartActivity(typeof(MainActivity));
}
}
SplashActivity 启动 MainActivity 可以启动 SpecialActivity
[Activity (Label = "MainActivity", Icon = "@mipmap/icon")]
public class MainActivity : Activity
{
protected override void OnCreate (Bundle savedInstanceState)
{
base.OnCreate (savedInstanceState);
SetContentView (Resource.Layout.Main);
Button button = FindViewById<Button> (Resource.Id.myButton);
button.Click += delegate {
//Fake a login status
var editor = GetSharedPreferences ("Login", Android.Content.FileCreationMode.Private);
var edit = editor.Edit ();
edit.PutBoolean ("login", true);
edit.Apply();
StartActivity(typeof(SpecialActivity));
};
}
}
后退按钮不会返回到SplashActivity,因为splash 不在堆栈历史记录中。如果你点击按钮,SpecialActivity 就会启动。
[Activity (Label = "SpecialActivity")]
public class SpecialActivity : Activity
{
ISharedPreferences myPrefs;
Button logoutButton;
protected override void OnCreate (Bundle savedInstanceState)
{
base.OnCreate (savedInstanceState);
SetContentView (Resource.Layout.Special);
logoutButton = FindViewById<Button> (Resource.Id.logoutButton);
myPrefs = GetSharedPreferences ("Login", Android.Content.FileCreationMode.Private);
logoutButton.Click += delegate {
var edit = myPrefs.Edit ();
edit.PutBoolean ("login", false);
edit.Apply();
logoutButton.Text = "Logout / Back Button will work now";
};
}
public override void OnBackPressed()
{
var isLoggedIn = myPrefs.GetBoolean("login", false);
if (!isLoggedIn)
{
base.OnBackPressed ();
Finish ();
} else {
logoutButton.Text = "Click me to log out first!";
}
}
}
在您通过单击“注销”按钮之前,后退按钮将不起作用,一旦注销,后退按钮将返回到MainActivity
一旦返回MainActivity,后退按钮将退出应用程序,因为没有堆栈历史记录并且我们不会覆盖OnBackPressed。