Return 值不同 Activity

Return value to a different Activity

我有一个应用程序,基本上看起来像附图中的设计。 可以看到,活动有4个,部分活动有碎片。

我想将测试的答案返回给用户的个人资料。 到目前为止,我一直在将结果上传到服务器并让应用程序在用户每次返回 ProfileActivity 时更新用户的个人资料,但这似乎是一种资源浪费。

应用程序中是否有执行此操作的模式或方法? 我查看了 this:如果我能以某种方式 link 两个 startActivityForResult() 似乎可行。

我研究了使用 this question 中描述的委托模式,但我无法将 UserFragment 的实例获取到 TestActivity.

我希望有人能给我指出正确的方法。

一种方法是使用 startActivityForResult() 不要完成任何 Activity

startActivityForResult() 之前开始所有活动,然后根据您的情况完成 activity

使用 onActivityResult()

将结果传回之前的 activity

然后对于片段,您可以将片段对象存储在 ProfileActivity 中。 在 Fragment 写入方法中更新 UI

因此您可以使用片段对象访问该方法

class ProfileActivity extends ......
{
  @override
  public void onActivityResult(....)
  {
    .....
    frgamnetObject.updateUI();
    ....
  }
}

假设您从上一页获得一个整数值:

创建 class :

public class GenericUtility {

public static int getIntFromSharedPrefsForKey(String key, Context context)
{
    int selectedValue = 0;

    SharedPreferences prefs = context.getSharedPreferences("com.your.packagename", Context.MODE_PRIVATE);
    selectedValue = prefs.getInt(key, 0);

    return selectedValue;
}

public static boolean setIntToSharedPrefsForKey(String key, int value, Context context)
{
    boolean savedSuccessfully = false;

    SharedPreferences prefs = context.getSharedPreferences("com.your.packagename", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = prefs.edit();

    try
    {
        editor.putInt(key, value);
        editor.apply();
        savedSuccessfully = true;
    }
    catch (Exception e)
    {
        savedSuccessfully = false;
    }

    return savedSuccessfully;
}

public static String getStringFromSharedPrefsForKey(String key, Context context)
{
    String selectedValue = "";

    SharedPreferences prefs = context.getSharedPreferences("com.your.packagename", Context.MODE_PRIVATE);
    selectedValue = prefs.getString(key, "");

    return selectedValue;
}

public static boolean setStringToSharedPrefsForKey(String key, String value, Context context)
{
    boolean savedSuccessfully = false;

    SharedPreferences prefs = context.getSharedPreferences("com.your.packagename", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = prefs.edit();

    try
    {
        editor.putString(key, value);
        editor.apply();
        savedSuccessfully = true;
    }
    catch (Exception e)
    {
        savedSuccessfully = false;
    }

    return savedSuccessfully;
}
}

而不是为其设置 int 值:

GenericUtility.setIntToSharedPrefsForKey("selected_theme", 1, getApplicationContext());

GenericUtility.setIntToSharedPrefsForKey("selected_theme", 1, MyActivity.this))

并且在您想要结果的第一个 activity 中:

int selectedValue = GenericUtility.getIntFromSharedPrefsForKey("selected_theme", getApplicationContext());

int selectedValue = GenericUtility.getIntFromSharedPrefsForKey("selected_theme", MyActivity.this);
如果没有值,

selectedValue 将 return 默认值。 PS 将 class 中的 int 更改为 String 以相应地获取和设置结果。