两个日期选择器片段 - 如何单独编辑日期?

时间:2016-06-09 20:43:25

标签: android date picker

我正在关注日期选择器Android教程。不幸的是,在做完之后,我意识到它只适用于我的一个文本字段,说实话,我不知道如何将它应用到另一个,DateEdit2。也就是说,单击DateEdit1或DateEdit2我编辑DateEdit1。我理解这来自设置日期的功能,但任何尝试更改或传递按钮作为参数都会导致错误,因为这些方法无法以这种方式编辑。有什么想法吗?

这是代码:

JsonFormat

提前谢谢你, 约翰

2 个答案:

答案 0 :(得分:1)

在活动中制作全局public boolean isDateEdit1;

在来自onClickListener的{​​{1}}中,在致电DateEdit1之前,请设置showTruitonDatePickerDialog(View v)

在来自isDateEdit1 = true;的{​​{1}}中,在致电onClickListener之前,请设置DateEdit2

然后,在showTruitonDatePickerDialog(View v)

isDateEdit1 = false;

答案 1 :(得分:0)

我创建了另一个类,它使用另一个名称扩展 DialogFragment 并使用了不同的函数:

public void showTruitonDatePickerDialog(View v) {
    DialogFragment newFragment = new DatePickerFragment();
    newFragment.show(getSupportFragmentManager(), "datePicker");
}

public void datePickerDialog(View v) {
    DialogFragment newFragment = new SecondDatePickerFragment();
    newFragment.show(getSupportFragmentManager(), "datePicker1");
}

public static class DatePickerFragment extends DialogFragment implements
        DatePickerDialog.OnDateSetListener {

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Use the current date as the default date in the picker
        final Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH);
        int day = c.get(Calendar.DAY_OF_MONTH);

        // Create a new instance of DatePickerDialog and return it
        return new DatePickerDialog(getActivity(), this, year, month, day);
    }

    public void onDateSet(DatePicker view, int year, int month, int day) {
        // Do something with the date chosen by the user
        DateEdit1.setText(DateEdit1.getText() + " " 
              + day + "/" + (month + 1) + "/" + year);
    }
}

public static class SecondDatePickerFragment extends DialogFragment implements
        DatePickerDialog.OnDateSetListener {

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Use the current date as the default date in the picker
        final Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH);
        int day = c.get(Calendar.DAY_OF_MONTH);

        // Create a new instance of DatePickerDialog and return it
        return new DatePickerDialog(getActivity(), this, year, month, day);
    }

    public void onDateSet(DatePicker view, int year, int month, int day) {
        // Do something with the date chosen by the user
        DateEdit2.setText(DateEdit2.getText() + " "
            + day + "/" + (month + 1) + "/" + year);
    }
}

这不是很好,但对我有用。 因此,在第一个 onClickListener() 上调用 showTruitonDatePickerDialog(),然后在第二个 onClickListener() 上调用 datePickerDialog()