2

Is there a way to send updated data to a parent activity when back is pressed? I'd like to update the data in the bundle, but I don't see how I would access it.

For example, I have a gallery activity that opens an image viewer. Say a user scrolls through a dozen images and then backs out to the gallery. It would be ideal to update the focal image in the gallery with the last image they viewed.

At the moment I can't think of how to do so without a global setting.

Here's pseudo code of what I'd like to do (although this obviously wouldn't work):

Child:

@Override
public void onBackPressed() {
    getIntent().setData(currentImage);  // Not the right intent, obviously
    super.onBackPressed();
}

Parent:

@Override
public void onResume()
{
    super.onResume();
    Uri photoFocus = getIntent().getData();
    if (photoFocus != null)
        setPhotoFocus(photoFocus);
}
4

5 回答 5

11

你可以做

startActivityForResult()

当您开始 childactivity 时,从您的父活动。onBackPressed,您可以在 childActivity 中调用 setResult()。

在 parentActivity 代码将来到回调:

protected void onActivityResult(int requestCode, int resultCode, Intent data) { }

您可以在其中提取 setResult 方法中的结果集

或者

使用共享首选项

于 2013-08-26T07:20:17.970 回答
2

创建一个公共类:

public class Values {

    public static Uri uri = null;

}

孩子:

@Override
public void onBackPressed() {
    //Set Values.uri here
    super.onBackPressed();
}

家长:

@Override
public void onResume()
{
    super.onResume();
    //Get Value.uri here and assign
}
于 2013-08-26T07:22:02.837 回答
0

您还可以将数据对象保留为参考点(甚至是静态的)并在 onBackPressed() 方法中对其进行更新,并且在父 Activity 中,您可以通过 onResume() / onRestart() 方法获取该数据。不知何故,这是一个利用活动生命周期绕过以意图传递数据的机制的一般概念。

于 2013-08-26T07:18:49.590 回答
0

您还可以使用共享首选项来存储数据,然后在父活动中获取它,请参阅这篇关于共享首选项的帖子如何在 Android 中使用 SharedPreferences 来存储、获取和编辑值

于 2013-08-26T07:19:36.360 回答
0

你应该尝试onSaveInstanceState而不是onBackPressed.

onSaveInstanceState提供对捆绑包的访问权限。

于 2013-08-26T07:15:21.727 回答