我找不到明确的答案。
在Android片段中实现2个日期选择器的最简单方法是什么?
当用户点击每个按钮时,只需要对话框,当用户选择一个按钮时,只需要一个返回值。
答案 0 :(得分:1)
试试这个,
按钮点击:
int select_date = 1;
et_date1.setOnClickListener(new View.OnClickListener() {
@Override
select_date = 1;
showDatePickerDialog();
}
});
et_date2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
select_date = 2;
showDatePickerDialog();
}
});
showDatePickerDialog:
private void showDatePickerDialog() {
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getChildFragmentManager(), "datePicker");
}
DatePickerFragment:
public static class DatePickerFragment extends DialogFragment implements
DatePickerDialog.OnDateSetListener {
@NonNull
@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
DatePickerDialog date_picker = new DatePickerDialog(getActivity(), this, year, month, day);
return date_picker;
}
public void onDateSet(DatePicker view, int year, int month, int day) {
// Do something with the date chosen by the user
String str_date = day + "/" + (month + 1) + "/" + year;
if (select_date == 1) {
et_date1.setText(str_date);
} else {
et_date2.setText(str_date);
}
select_date = 0;
}
}
答案 1 :(得分:1)
您应该始终提供一系列代码,以便每个人都能更轻松地了解您的需求以及如何正确地为您提供帮助。
但是,这是一个简单的调用方法,它将生成一个DatePicker:
private void showDatePickerDialog(final EditText view) {
/**
* @author Mohammed Al-Safwan
* **/
final Calendar c = Calendar.getInstance();
int mYear = c.get(Calendar.YEAR); // current year
int mMonth = c.get(Calendar.MONTH); // current month
int mDay = c.get(Calendar.DAY_OF_MONTH); // current day
DatePickerDialog datePickerDialog = new DatePickerDialog(mContext, new DatePickerDialog.OnDateSetListener() {
/**
*
* @param year selected year.
* @param month selected month.
* @param day selected day.
* **/
@Override
public void onDateSet(DatePicker datePicker, int year, int month, int day) {
}
}, mYear, mMonth, mDay);
// finally, show your dialog
datePickerDialog.show();
}