当用户点击DialogFragment
DatePicker
来显示EditText
如何在同一EditText
中显示所选日期。
我使用this作为参考。
DatePickerFragment.java:
public 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);
}
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
Calendar c = Calendar.getInstance();
c.set(year, monthOfYear, dayOfMonth);
SimpleDateFormat sdf = new SimpleDateFormat("dd MMMM yyyy");
String formattedDate = sdf.format(c.getTime());
Toast.makeText(getActivity(), formattedDate, Toast.LENGTH_LONG).show();
}
}
片段:
editDate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
android.support.v4.app.DialogFragment dialogFragment = new DatePickerFragment();
dialogFragment.show(getFragmentManager(), "datePicker");
}
});
当我点按EditText时,它会在 DatePicker
中显示Toast
和所选日期。但我无法弄清楚如何在EditText
?
答案 0 :(得分:1)
你可以这样做 -
EditText edttxt_date = (EditText) findViewById(R.id.date);
edttxt_date.setText(formattedDate);
Toast.makeText(getBaseContext(), formattedDate, Toast.LENGTH_SHORT).show();
或 您也可以使用日历和 DatePickerDialogFragment 来显示类似这样的时间并将相应的值返回到您的片段。
DateFormat dateFormat = DateFormat.getDateInstance();
edttxt_date.setText(dateFormat.format(cal.getTime()));
希望它有所帮助!!
答案 1 :(得分:0)
只需替换它:
Toast.makeText(getActivity(), formattedDate, Toast.LENGTH_LONG).show();
行或输入此行以在 EditText:
中显示日期EditText date=(EditText)find(...);
date.setText(formattedDate);
答案 2 :(得分:0)
在MainFragment类中添加DatePickerFragment类。 调用public void onDateSet()后,调用同一个类中的方法来更新editText字段。
public MainFragment extents Fragment{
.....
updateDateField(String formattedDate){
editDate.setText(formattedDate);
}
public class DatePickerFragment extends DialogFragment
implements DatePickerDialog.OnDateSetListener {
....
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
Calendar c = Calendar.getInstance();
c.set(year, monthOfYear, dayOfMonth);
SimpleDateFormat sdf = new SimpleDateFormat("dd MMMM yyyy");
String formattedDate = sdf.format(c.getTime());
updateDateField(formattedDate);
}
}
}