2016-11-15 41 views
0

我做了一個按鈕來打開日期和時間選擇器,但必須選中一個複選框才能激活我的按鈕。沒有複選框,它可以正常工作,chekbox選中或取消選中,它不會打開日期選擇器。你能告訴我爲什麼嗎?需要複選框以允許按下按鈕 - 如果不工作

protected void onCreate(Bundle savedInstanceState) 
{ 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_new); 
    getSupportActionBar().setDisplayHomeAsUpEnabled(true); 

    pick_date = (Button) findViewById(R.id.pick_date); 
    tv_result = (TextView) findViewById(R.id.tvdate_result); 
    CheckBox fixed_date_flag = (CheckBox) findViewById(R.id.fixed_date); 
    final boolean checked = (fixed_date_flag).isChecked(); 

    if(checked){ 
    pick_date.setOnClickListener(new View.OnClickListener() 
    { 
     @Override 
     public void onClick(View view) 
     { 
      Calendar c = Calendar.getInstance(); 
      year = c.get(Calendar.YEAR); 
      month = c.get(Calendar.MONTH); 
      day = c.get(Calendar.DAY_OF_MONTH); 

      DatePickerDialog datePickerDialog = new DatePickerDialog(NewActivity.this, NewActivity.this, year, month, day); 
      datePickerDialog.show(); 
     } 
    });} 
} 

@Override 
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) 
{ 
    yearFinal = year; 
    monthFinal = month + 1; 
    dayFinal = dayOfMonth; 

    Calendar c = Calendar.getInstance(); 
    hour = c.get(Calendar.HOUR); 
    minute = c.get(Calendar.MINUTE); 

    TimePickerDialog timePickerDialog = new TimePickerDialog(NewActivity.this, NewActivity.this, hour, minute, DateFormat.is24HourFormat(this)); 
    timePickerDialog.show(); 

} 

@Override 
public void onTimeSet(TimePicker view, int hourOfDay, int minute) 
{ 
    hourFinal = hourOfDay; 
    minuteFinal = minute; 
    tv_result.setText(
      "year: " + yearFinal + "\n" + 
        "month: " + monthFinal + "\n" + 
        "day: " + dayFinal + "\n" + 
        "hour: " + hourFinal + "\n" + 
        "minute: " + minuteFinal); 
} 

}

+0

您需要在複選框上設置checkchangelistener來獲取複選框的當前狀態,只要它發生變化 –

+0

您有調試嗎?通過調試你可以看到「checked」的值 –

回答

0

你的問題很簡單:

在創建活動中,如果複選框被選中,您將可以檢查。如果此值爲true(但不是true),則將單擊偵聽器添加到datePicker。所以,選擇器沒有一個點擊監聽器!這意味着當你點擊選擇器時,即使複選框被選中,它也沒有添加監聽器。然而

pick_date.setOnClickListener(new View.OnClickListener() 
{ 
    @Override 
    public void onClick(View view) 
    { 
     if((fixed_date_flag).isChecked()){ 
      Calendar c = Calendar.getInstance(); 
      year = c.get(Calendar.YEAR); 
      month = c.get(Calendar.MONTH); 
      day = c.get(Calendar.DAY_OF_MONTH); 

      DatePickerDialog datePickerDialog = new DatePickerDialog(NewActivity.this, NewActivity.this, year, month, day); 
      datePickerDialog.show(); 
     } 
    } 
}); 

,我認爲這是一個更好的選擇,以創建一個分離中國社會科學院實現OnClickListener接口:

你必須移動if語句中的onClick方法中,像這樣:

EDITED所以在構造函數中,你可以初始化datepicker,作爲這個新類的私有變量,onClick方法你只能調用.show()方法(如果複選框被選中,obbiusly)

希望它有幫助!

+0

它還沒有工作,但是謝謝。我會嘗試做一個支票監聽器,但我不知道 –

+0

對不起,我忘了更新檢查變量! – kelmi92

+0

我將用解決方案編輯答案。 – kelmi92