【发布时间】:2020-04-06 11:38:26
【问题描述】:
所以我将 SharedPreference 编码到(活动 1)中,它允许用户选择在应用启动时首先向他们呈现的活动。代码运行良好,但如果用户想要更改他们的选择怎么办?当用户按下后退按钮返回(活动 1)时,它会自动将他们重定向到他们之前选择的活动。当用户单击调用 onBackPressed() 方法的活动 2 上的“后退按钮”时,如何重置/清除(活动 1)中的共享首选项?
活动一
final SharedPreferences sharedPref = getPreferences(MODE_PRIVATE);
int choice = sharedPref.getInt("default_activity", -1);
if (choice == -1) {
// show the option to choose the default activity to the user
// e.g. dialog with list, then save the corresponding choice to
// shared preference
String[] activities = { "Activity 1", "Activity 2", "Activity 3" };
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setAdapter(
new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, activities),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("default_activity", which);
editor.apply();
launchActivity(which);
}
}).show();
} else {
// start the activity and close this activity
launchActivity(choice);
}
}
private void launchActivity(int choice) {
switch (choice) {
case 0:
startActivity(new Intent(this, Activity_1.class));
break;
case 1:
startActivity(new Intent(this, Activity_2.class));
break;
case 2:
startActivity(new Intent(this, Activity_3.class));
break;
}
finish();
}
活动 2
@Override
public void onBackPressed() {
super.onBackPressed();
Intent i = new Intent (getApplicationContext(), PreActivity.class);
startActivity(i);
}
【问题讨论】:
标签: android-studio android-activity sharedpreferences onbackpressed