2013-08-06 64 views
1

我已经知道如何使用这个代码,以禁用按钮:如何在一天内点击一次后禁用按钮并在第二天重新启用按钮?

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

我想一旦点击了一天禁用按钮,然后启用按钮第二天机器人。换句话说,如果按钮今天点击一次,它将在明天之前变为禁用状态。有任何想法吗?

+0

在点击侦听器中,保存它在SharedPreferences中被点击的日期,然后将当前日期与onResume()的共享首选项中的值进行比较以启用或禁用该按钮。 – Simon

回答

1

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

要将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检索的日期时间再次,你可以尝试:

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

0

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

坚持数据的方式取决于您。

1

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

然后在onResume活动或interval of a custom timer之后,您可以从共享首选项中获取存储时间,从当前时间中减去它,然后查看该数字是否大于day

if (now - storedTime > DateUtils. DAY_IN_MILLIS) { 
    b.setEnabled(true); 
} 
相关问题