【问题标题】:How do you safely share code that needs an Android Activity?如何安全地共享需要 Android Activity 的代码?
【发布时间】:2014-11-25 07:50:44
【问题描述】:

我想避免重复需要在 Activity 上使用方法的代码(比如 getActivity().getString()) 。

创建一个保留对 Activity 的引用的对象似乎不起作用(对象一直在重新创建,并且在需要时对 Activity 的任何引用都是空的。)

// This won't work, it seems
public class MyUtils {
    public MyUtils(Activity activity) {
      this.activity = activity;
    }
    public String getSomeStuff() {
       return this.activity.getString(R.string.foo);
    }
}

// In a Fragment created by the activity

MyUtils utils = new MyUtils(getActivity());
myUtils.getSomePref();

那么如何避免重复代码呢? 是否有一种“安全”的方式来分解需要 Activity 的代码? 您是否应该将所有代码放在 Activity 本身中,并从 Fragments 中进行转换?

编辑:为了澄清我的问题,我特别在寻找一种在片段之间共享代码的方法,这些代码在 Activity 中显示为选项卡(使用 TabsPagerAdapter)。 他们都需要访问一些保存为几个首选项的结构化数据。 当片段不可见时,他们还需要在 onSharedPreferencesChanged 事件处理程序中访问此数据。 根据我的经验,每当我停止和恢复应用程序、在片段之间导航、更改首选项等......我的活动的所有变量都是空的。

【问题讨论】:

  • 为什么每次活动恢复时不刷新变量?片段支持onCreateonResume等方法
  • 还有,这真的是代码重复吗?
  • 除了getString(),你还有什么真实的例子吗?这真的不是代码重复。您只是将getActivity().getString() 函数与另一个同样重复的函数进行了不必要的包装。
  • 好吧,在我的例子中,我使用了许多 SharedPreferences,并且我想包装基于软编码字符串获取 stome 首选项的代码。所以是的,这是为了避免代码重复。

标签: android


【解决方案1】:

另一种方法是将活动作为参数提供给每个实用程序函数。 (您甚至可以通过这种方式将它们设为静态。)另外,如果您不需要 Activity 特定的功能,请使用 Context 代替更通用的方法。

public class MyUtils {
    public static String getSomeStuff(Context a) {
       return a.getString(R.string.foo);
    }

    // more static utility function here
}

【讨论】:

  • 在这种情况下(以及许多其他情况),最好使用 Context 而不是 Activity(Activity 扩展 Context)。例如,您无法访问 Service 中的 Activity,但您可以使用 getApplicationContext() 获取 Context 并在那里使用此函数。
  • @mus65 好点,但你可以使用ServiceName.thisthis,因为Service 也扩展了Context。在大多数情况下,这可能比getApplcationContext() 更好。 Kupsef,如果你改变它,那么你会得到我的支持,因为我正要给出相同的答案,但 Context
  • @codeMagic: Which would probably be better in most cases than getApplcationContext() 来源?
  • @njzk2 以this SO post 开头并通读其中包含的链接
  • @njzk2 不客气。 This blog post 隐藏在上一个链接的评论中,但绝对值得一读。可能应该被编辑到他的答案中。
【解决方案2】:

我通常使用 SuperActivity 共享我的 SharedPreferences:

public class SuperActivity extends Activity {
    protected SharedPreferences prefs;
    public static final String PREFS_FILE = "PreferencesFile";
    public static final String STRING_VALUE_KEY = "StringVal";

    protected void onResume() {
        super.onResume();
        prefs = this.getSharedPreferences(PREFS_FILE, 0);
    }

    public String getStringValue() {
        prefs.getString("STRING_VALUE_KEY", "")
    }
}

public class SomeActivity extends SuperActivity {
    ....
}

然后你可以调用:

getActivity().getStringValue();

从我想的任何地方..

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多