应用程序重启后禁用按钮

时间:2017-11-02 15:52:02

标签: android

我的应用程序有一个按钮,如果该日期与之前单击的那天相同,则会禁用该按钮,但如果我重新启动应用程序,则该按钮会重新联机,即使该日期是禁用它的日期。

shDayMed = sh.getInt("daymed", calendar.get(Calendar.DAY_OF_MONTH));
int day = shDayMed;
int dayAtual = calendar.get(Calendar.DAY_OF_MONTH);
if (day != dayAtual) {
    save.setEnabled(true);
    pesohj.setEnabled(true);
} else {
    save.setEnabled(false);
    pesohj.setEnabled(false);
}

我认为这是错误的部分,如果当天不是当天,应该设置按钮为真,但它的反面呢......

2 个答案:

答案 0 :(得分:1)

存储点击SharedPreferences的最后日期,然后当您启动Activity时,检索该值以确定是否应禁用或启用该按钮。

答案 1 :(得分:1)

如果您想跟踪某个值,即使应用已关闭并重新启动,也必须使用SharedPreferences。关闭应用程序时,您将删除代码中的变量。

将变量保存到共享首选项,如下所示:

SharedPreferences sharedPrefs = PreferenceManager.getDeafaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPrefs.edit()
editor.putInt("Day", Calendar.DAY_OF_THE_MONTH);
editor.apply()

然后使用:

检索它
int dayAtual = sharedPrefs.getInt("Day", -1 /* this is the default value if the pref isn't found*/)

希望这有助于你。

相关问题