我认为最好的方法是像 ZerO 所说的那样使用 sharedPreferences。例如,每次用户打开按钮所在的活动时,检查 sharedPrefs,例如,保存日期。单击按钮后,保存当前日期。并且每次您打开活动并且保存的日期等于当前日期时,不允许单击按钮(您可以使用 View.GONE 或 setEnabled(false) 进行操作):
private boolean firstTimeUsed = false;
private String firstTimeUsedKey="FIRST_TIME";
private String sharedPreferencesKey = "MY_PREF";
private String buttonClickedKey = "BUTTON_CLICKED;
private SharedPreferences mPrefs;
private long savedDate=0;
初始化这些以在 onCreate() 中设置全局变量:
mPrefs = getSharedPreferences(sharedPreferencesKey, Context.MODE_PRIVATE);
savedDate = mPrefs.getLong(buttonClickedKey,0);
firstTimeUsed = mPrefs.getBoolean(firstTimeUsedKey,true);//default is true if no value is saved
checkPrefs();
mButton.setOnClickListener(new OnClickListener(){
@Override
public void OnClick(View v){
//things You want to do, after that:
saveClickedTime();
}
});
用你的方法检查时间:
private void checkPrefs(){
if(firstTimeUsed==false){
if(savedDate>0){
//create two instances of Calendar and set minute,hour,second and millis
//to 1, to be sure that the date differs only from day,month and year
Calendar currentCal = Calendar.getInstance();
currentCal.set(Calendar.MINUTE,1);
currentCal.set(Calendar.HOUR,1);
currentCal.set(Calendar.SECOND,1);
currentCal.set(Calendar.MILLISECOND,1);
Calendar savedCal = Calendar.getInstance();
savedCal.setTimeInMillis(savedDate); //set the time in millis from saved in sharedPrefs
savedCal.set(Calendar.MINUTE,1);
savedCal.set(Calendar.HOUR,1);
savedCal.set(Calendar.SECOND,1);
savedCal.set(Calendar.MILLISECOND,1);
if(currentCal.getTime().after(savedCal.getTime()){
mButton.setVisibility(View.VISIBLE);
}else if(currentCal.getTime().equals(savedCal.getTime()){
mButton.setVisibility(View.GONE);
}
}
}else{
//just set the button visible if app is used the first time
mButton.setVisibility(View.VISIBLE);
}
}
每次按钮可用并被点击时,将日期保存回 sharedPrefs:
private void saveClickedTime(){
Editor mEditor = mPrefs.edit();
Calendar cal = Calendar.getInstance();
long millis = cal.getTimeInMillis();
mEditor.putLong(buttonClickedKey,millis);
mEditor.putBoolean(firstTimeUsedKey,false); //the button is clicked first time, so set the boolean to false.
mEditor.commit();
//hide the button after clicked
mButton.setVisibility(View.GONE);
}
这只是从头开始,目前尚未测试,但应该让您了解如何做到这一点。