我确定我遗漏了一些关于后退堆栈及其工作方式的信息,或者我可能只需要在这里添加几行,但我只是想让我的后退按钮功能正常工作。
Activity A 使用通过 intent extra 传递的 ID 发出 API 请求来填充它的字段(这在 onCreate 中完成)。 Activity B 是从 Activity A 打开的,但是在返回到 Activity A 时, Intent 中没有 id,因此无法发出请求。
如何设置我的导航以便在启动 Activity B 时保留创建 Activity A 的 Intent ,并在按下后退按钮时重新发送?任何接近于此的功能,如果更简单,也可能没问题。
截至目前,当我开始 Activity A 时,我没有做任何特别的事情。 以下是我在 Activity B 中设置后退按钮的方法(以及在我的 list 中将父 Activity 指定为 Activity A):
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar5);
setSupportActionBar(toolbar);
// Make sure there is a back button
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
提前感谢您的帮助。
我将我的 ID 附加到 Intent 并启动 Activity A 的地方:
Intent detailsIntent = new Intent(context, ViewObjActivity.class);
detailsIntent.putExtra("objId", objId);
context.startActivity(detailsIntent);
我从 Activity A 的 onCreate 中的 Intent 中检索我的 ID 的位置:
// Get data from extras
Intent detailsIntent = getIntent();
mObjID = detailsIntent.getIntExtra("objId", -1);
修复
经过一番挖掘,我发现默认的后退按钮功能不是很好。通过使用以下内容覆盖处理程序,我能够避免存储 ID,因为没有调用 onCreate - Activity 的先前状态已经存储。
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId()== android.R.id.home) {
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
最佳答案
您可以考虑使用此选项。
当从Activity A 变为B的 Intent 被激活时,onPause()方法将被执行。
因此,onPause() 方法将是您保存 Activity 状态的好地方。
public static final String SHARED_PREFERENCE = "";
protected void onPause(){
super.onPause();
SharedPreferences settings = getSharedPreferences(SHARED_PREFERENCE,0);
SharedPreferences.Editor editor = settings.edit();
editor.clear();
editor.putInt("ID", id);
editor.commit();
}
您将必须恢复您的SharedPreferences onResume() 和onCreate()。
关于Android Back/Up 按钮并保留之前的 Intent ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36508179/