2017-01-03 92 views
2

我有一個帶今日日期的textview,當onclick將文本視圖設置爲next或prev date時,有兩個按鈕。現在,如果textview顯示當前日期,我想禁用上一個按鈕。也就是說,如果今天的日期是1/3,用戶可以去1/4和之後,並在未來的日期之間切換。但用戶在當前日期之前不能進入1/2或任何日期。如何在當前日期之前禁用先前日期的按鈕? Android

 tvShowDate = (TextView) findViewById(R.id.tvShowDate); 

    long date = System.currentTimeMillis(); 

    final SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMMdd"); 
    String dateString = sdf.format(date); 
    tvShowDate.setText(dateString); 


    ivPrevDate = (ImageView) findViewById(R.id.ivPrevDate); 
    ivNextDate = (ImageView) findViewById(R.id.ivNextDate); 


    final Calendar c = Calendar.getInstance(); 
    final String[] formattedDate = {sdf.format(c.getTime())}; 

    ivPrevDate.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View v) { 

      c.add(Calendar.DATE, -1); 
      formattedDate[0] = sdf.format(c.getTime()); 

      Log.v("PREVIOUS DATE : ", formattedDate[0]); 
      tvShowDate.setText(formattedDate[0]); 
     } 
    }); 


    ivNextDate.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View v) { 

      c.add(Calendar.DATE, 1); 
      formattedDate[0] = sdf.format(c.getTime()); 

      Log.v("NEXT DATE : ", formattedDate[0]); 
      tvShowDate.setText(formattedDate[0]); 

     } 
    }); 

回答

1

試試這個功能:

public boolean Check_valid_date(CharSequence d) { 
    SimpleDateFormat sdf = new SimpleDateFormat("dd MMMM yyyy"); 
    Date date_new = null; 
    try { 
     date_new = sdf.parse(d.toString()); 
     Date current_date = new Date(); 
     current_date = removeTime(current_date); 
     Log.d("CurentDate", current_date.toString()); 
     Log.d("NEW date", date_new.toString()); 
     if (current_date.equals(date_new)) { 
      return true; 
     } 
     return current_date.before(date_new); 
    } catch (ParseException e) { 
     e.printStackTrace(); 
    } 
    return false; 
} 

public Date removeTime(Date date) { 
    Calendar cal = Calendar.getInstance(); 
    cal.setTime(date); 
    cal.set(Calendar.HOUR_OF_DAY, 0); 
    cal.set(Calendar.MINUTE, 0); 
    cal.set(Calendar.SECOND, 0); 
    cal.set(Calendar.MILLISECOND, 0); 
    return cal.getTime(); 
} 

使用它作爲:

Calendar calendar = Calendar.getInstance(); 
calendar.set(year, month, day); 
CharSequence date = DateFormat.format("dd MMMM yyyy", calendar.getTime()); 
//pass your selected date.. 
boolean check = Check_valid_date(date); 


if(check){ 
    //date is after current date 
    } 
else{ 
    //date is before current date 
    //disable button 
    } 
+0

謝謝您的回答 – JerryKo

0

爲此在codition

myButton.setEnabled(false) 
相關問題