Android Back/Up 按钮并保留之前的意图

Android Back/Up button and preserving previous intent

我确定我遗漏了一些关于后退堆栈及其工作方式的信息,或者我可能只需要在这里添加几行但我只是想让我的后退按钮功能正常工作。

Activity A 使用通过 intent extra 传递的 ID 发出 API 请求来填充它的字段(这是在 onCreate 中完成的)。 ActivityB是从ActivityA打开的,但是回到ActivityA时,intent中没有id,所以无法发出请求。

如何设置我的导航,以便在启动 Activity B 时保留创建 Activity A 的意图,并在按下后退按钮时重新发送?任何接近于此的功能,如果更简单,也可能没问题。

截至目前,我在开始 Activity A 时没有做任何特别的事情。 这是我在 Activity B 中设置我的后退按钮的方法(以及在我的清单中将父级 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 附加到意图并开始 Activity A:

Intent detailsIntent = new Intent(context, ViewObjActivity.class);
detailsIntent.putExtra("objId", objId);
context.startActivity(detailsIntent);

我从 Activity A 的 onCreate 中的意图中检索我的 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);
}

您可以考虑改用这个选项。

ActivityA到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()