【发布时间】:2020-07-02 18:17:59
【问题描述】:
我找到了这个视频 (https://www.youtube.com/watch?v=MZjIhaMKnlo) 并复制了(几乎)准确的代码来每天一次为用户分配一些任务,如下所示:
Calendar calendar = Calendar.getInstance();
int currentDay = calendar.get(Calendar.DAY_OF_MONTH);
SharedPreferences settings = this.getActivity().getSharedPreferences("PREFS", 0);
int lastDay = settings.getInt("day",0);
if (lastDay != currentDay) {
SharedPreferences.Editor editor = settings.edit();
editor.putInt("day", currentDay);
editor.commit();
str1 = "oic_" + random.nextInt(76);
int id1 = getResources().getIdentifier("com.codepath.wmgf8:drawable/" + str1, null, null);
daily_goal1.setBackgroundResource(id1);
}
唯一的区别是我用this.getActivity().getSharedPreferences而不是getSharedPreferences,因为我使用的是Fragment。
但是,每次我打开应用程序时,它都会分配随机图像。
有人可以帮我解决这个问题吗?
编辑
发现Fragment中无法传递activity...
似乎唯一的方法是完全创建一个新活动。
如果有其他选择,请告诉我!
【问题讨论】:
标签: android android-studio android-fragments calendar sharedpreferences