android - 如何在一天点击一次后禁用按钮并在第二天启用按钮?

标签 android button

我已经知道如何使用这段代码禁用按钮:

b.setFocusable(false);
b.setEnable(false);

我想在当天点击该按钮后禁用该按钮,然后在第二天在 android 中启用该按钮。换句话说,如果今天单击该按钮一次,它将在明天之前变为禁用状态。有什么想法吗?

最佳答案

在 SharedPreferences 中保存一个时间戳就足够了。如果您担心安全性,您可以使用加密库(请参阅 this SO link )并将日期时间保存在文件中,但这很可能是矫枉过正。

要将 SharedPreferences 与日期一起使用,很容易使用 java.util.Date 对象的格式化字符串(具有日期精度)。

例如,要将 java.util.Date 类作为格式化字符串持久化到 SharedPreferences:

//pre-condition: variable "context" is already defined as the Context object in this scope
String dateString = DateFormat.format("MM/dd/yyyy", new Date((new Date()).getTime())).toString();
SharedPreferences sp = context.getSharedPreferences("<your-app-id>", Context.MODE_PRIVATE);
Editor editor = sp.edit();
editor.putString("<your-datetime-label>", dateString);
editor.commit();

要再次从 SharedPreferences 中检索日期时间,您可以尝试:

//pre-condition: variable "context" is already defined as the Context object in this scope
SharedPreferences sp = context.getSharedPreferences("<your-app-id>", Context.MODE_PRIVATE);
String savedDateTime = sp.getString("<your-datetime-label>", "");
if ("".equals(savedDateTime)) {
    //no previous datetime was saved (allow button click)
    //(don't forget to persist datestring when button is clicked)
} else {
    String dateStringNow = DateFormat.format("MM/dd/yyyy", new Date((new Date()).getTime())).toString();
    //compare savedDateTime with today's datetime (dateStringNow), and act accordingly
    if(savedDateTime.equals(dateStringNow){
        //same date; disable button
    } else {
        //different date; allow button click
    }
}

这使得保留日期并再次检查它们变得相当简单。 您还可以存储系统的 timeInMillis,并在共享首选项中使用长值而不是日期的字符串表示。

关于android - 如何在一天点击一次后禁用按钮并在第二天启用按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18084733/

相关文章:

Android Library Declare-Styleable 运行时错误

android - 有没有在 Android Marshmallow 中以编程方式使用模式/密码解锁锁屏?

html - 按钮组在较小的屏幕上停止工作

Javascript - 更改变量

button - 单击显示按钮时应用程序崩溃,没有红色代码

python - 在PyQt5中使用QMessageBox重启我的游戏或退出应用程序

java - 如何停止占用麦克风

android - 如何使用 Android Jetpack App 启动库

html - 最强大的纯 CSS 按钮解决方案?

android - 如何更改开关小部件的高度?