检查onClickListener中按钮中的textdates是否相同

时间:2011-12-15 10:56:58

标签: java android date button

我有两个日期按钮。这两个按钮包含一个String作为文本。 如果有人点击按钮,则会出现一个日期选择器。在这个datepicker之后 我想检查两个按钮是否包含相同的日期字符串。 如果是这样,我想让两个按钮出现(在这两个按钮下面) timepickers。

First image when no date is choosen

This is what should happen

问题是,检查两个日期是否相等的方法,在点击按钮后首先自动启动。所以我必须单击两次按钮才能正确检查日期是否相等。

这是我的代码:

首先是onClickListeners

startDate.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {

        DateDialog dateStart = new DateDialog(startDate, mYear, mMonth, mDay);
        checkdates();

    }
});

endDate.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        DateDialog dateEnd = new DateDialog(endDate, mYear, mMonth, mDay);
        checkdates();
    }
});

其次,checkdates方法:

private void checkdates() {

    String firstdate = startDate.getText().toString();
    String seconddate = endDate.getText().toString();

    if (firstdate.equals(seconddate)) {
        row1.setVisibility(View.VISIBLE);
        row2.setVisibility(View.VISIBLE);
    } else {
        row1.setVisibility(View.INVISIBLE);
        row2.setVisibility(View.INVISIBLE);
    }
}

最后,在onClickListener中调用了类DateDialog:

public class DateDialog {

private int mMonth;
private int mYear;
private int mDay;
private Button txtButton;

public DateDialog(Button b, int year, int month, int day){
    txtButton = b;
    onCreateDialog(year, month, day);
}

protected Dialog onCreateDialog(int year, int month, int day) {
        DatePickerDialog dialog = new DatePickerDialog(NostradamusActivity2.parentcontext, mDateSetListener, year,
                month, day);
        dialog.show();
        return null;
}

// updates the date we display in the TextView
private void updateDisplay() {
    txtButton.setText(new StringBuilder()
            // Month is 0 based so add 1
            .append(mYear).append("-").append(mMonth + 1).append("-")
            .append(mDay).append(""));
}

private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
    public void onDateSet(DatePicker view, int year, int monthOfYear,
            int dayOfMonth) {
        mYear = year;
        mMonth = monthOfYear;
        mDay = dayOfMonth;
        updateDisplay();
    }
};
 }

1 个答案:

答案 0 :(得分:0)

您可以在interface类中定义DateDialog,如下所示:

public static interface DateDialogListener
{
     public void dialogDateChanged();
}

并将DateDialog类中的字段声明为

DateDialogListener dateListener;

并为其创建setter方法。

并且在updateDisplay()中也将此调用放在最后

if(dateListener != null)
dateListener.dialogDateChanged();

当您从onClick()内的按钮Activity打开对话框时,请像这样使用DateDialogListener

DateDialog dateStart = new DateDialog(startDate, mYear, mMonth,mDay);
dateStart.setDateListener( new DateDialogListener()
{
     public void dialogDateChanged()
     {
         checkdates(); 
     }     
});