我正在开发一款需要用户选择日期的应用(dd / mm / yyyy)。 我想在按钮单击时显示一个带有DatePicker的对话框。 一旦选择了日期,它必须在EditText中显示。
我使用的是Android Studio 2.2,使用min sdk的项目是23。
请帮我做必要的代码。
答案 0 :(得分:59)
予。在build.gradle中添加最新的appcompat库,时间为24.2.1
dependencies {
compile 'com.android.support:appcompat-v7:X.X.X'
// where X.X.X version
}
II。让您的活动扩展android.support.v7.app.AppCompatActivity
并实施DatePickerDialog.OnDateSetListener
界面。
public class MainActivity extends AppCompatActivity
implements DatePickerDialog.OnDateSetListener {
III。创建DatePickerDialog
设置上下文,监听器的实现以及日期选择器的开始年份,月份和日期。
DatePickerDialog datePickerDialog = new DatePickerDialog(
context, MainActivity.this, startYear, starthMonth, startDay);
IV。在按钮的单击事件监听器上显示对话框
((Button) findViewById(R.id.myButton))
.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
datePickerDialog.show();
}
});
答案 1 :(得分:16)
DatePickerDialog StartTime = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
Calendar newDate = Calendar.getInstance();
newDate.set(year, monthOfYear, dayOfMonth);
activitydate.setText(dateFormatter.format(newDate.getTime()));
}
}, newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH));
btn_checkin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
StartTime .show():
});
答案 2 :(得分:12)
它对我有用。如果要启用将来的选择时间,则必须删除最长日期。你需要做类似的事情。
btnDate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getSupportFragmentManager(), "datePicker");
}
});
public static class DatePickerFragment extends DialogFragment
implements DatePickerDialog.OnDateSetListener {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
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);
DatePickerDialog dialog = new DatePickerDialog(getActivity(), this, year, month, day);
dialog.getDatePicker().setMaxDate(c.getTimeInMillis());
return dialog;
}
public void onDateSet(DatePicker view, int year, int month, int day) {
btnDate.setText(ConverterDate.ConvertDate(year, month + 1, day));
}
}
答案 3 :(得分:7)
以下代码有效..
datePickerButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showDialog(0);
}
});
@Override
@Deprecated
protected Dialog onCreateDialog(int id) {
return new DatePickerDialog(this, datePickerListener, year, month, day);
}
private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int selectedYear,
int selectedMonth, int selectedDay) {
day = selectedDay;
month = selectedMonth;
year = selectedYear;
datePickerButton.setText(selectedDay + " / " + (selectedMonth + 1) + " / "
+ selectedYear);
}
};