0

I want to get several dates from the user in one activity. The activity implements onDateSetListener.

I have 4 buttons, each of which calls the showDialog function to display a DatePickerDialog. In the OnDateSet function, how do I differentiate between the 4 buttons? (as in, how do I check which button called this dialog).

I have similar a similar issue with TimePicker too but I'm guessing a solution for DatePicker will also work for TimePicker.

4

2 回答 2

1

您可以向 DatePicker 添加标签。创建对话框时,请执行以下操作:

mDatePickerDialog.getDatePicker().setTag(FIRST_DIALOG);

其中 FIRST_DIALOG 是例如整数或字符串;然后你只使用一个 onDateSetListener:

onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth)
{
    int code = (Integer) view.getTag(); //if you are using integers
    switch(code)
    {
        // switch between your datePicker
    }

}
于 2014-11-05T08:14:24.943 回答
0

Create CustomDatePickerDialog with Below code

public class CustomDatePickerDialog extends DatePickerDialog
{
    public CustomDatePickerDialog(Context context, OnDateSetListener callBack, int year, int monthOfYear, int dayOfMonth,View attachedView)
    {
        super(context, callBack, year, monthOfYear, dayOfMonth);
        getDatePicker().setTag(attachedView.getId());
    }

    public CustomDatePickerDialog(Context context, OnDateSetListener callBack, int year, int monthOfYear, int dayOfMonth)
    {
        super(context, callBack, year, monthOfYear, dayOfMonth);
    }

    public CustomDatePickerDialog(Context context, int theme, OnDateSetListener listener, int year, int monthOfYear, int dayOfMonth)
    {
        super(context, theme, listener, year, monthOfYear, dayOfMonth);
    }
}

Call it like below

btnSelectDate.setOnClickListener(new View.OnClickListener()
{
    @Override
    public void onClick(View view)
    {
        CustomDatePickerDialog customDatePickerDialog = new CustomDatePickerDialog(MainActivity.class,dateSetListener,2014,10,1,view);
        customDatePickerDialog.show();
    }
});

You will get which button invoked dialog like below in listener

DatePickerDialog.OnDateSetListener dateSetListener = new DatePickerDialog.OnDateSetListener()
{
    @Override
    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth)
    {
        int viewID = view.getTag();
        switch(viewID)
        {
            case R.id.btnDatePicker1;
            {
                //DO Something
            }
            case R.id.btnDatePicker2;
            {
                //DO Something
            }
        }
    }
};

Note : API Level 11 Required for getDatePicker() call in custom dialog

于 2014-11-05T08:21:15.263 回答