1

我已经知道如何使用以下代码禁用按钮:

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

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

4

3 回答 3

1

按下按钮时,您可以将当前时间保存到SharedPreferences中。收集当前时间的一种方法是使用System.currentTimeMillis

然后在活动的 onResume 期间或自定义计时器的间隔之后,您可以从共享首选项中获取存储的时间,从当前时间中减去它,然后查看该数字是否大于一天

if (now - storedTime > DateUtils. DAY_IN_MILLIS) {
    b.setEnabled(true);
}
于 2013-08-06T15:56:54.827 回答
1

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

要将 SharedPreferences 与 Dates 一起使用,使用 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 中检索dateTime,您可以尝试:

//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,并在共享首选项中使用长值而不是日期的字符串表示。

于 2013-08-06T16:13:05.367 回答
0

第一次按下按钮时,您需要将 dateTime 保留在某处。再次按下时,您将存储的日期时间与实际日期时间进行比较。

保留该数据的方式取决于您。

于 2013-08-06T15:52:46.617 回答