1
我已經創建了兩個不同的editText,以前的檢查日期和當前檢查日期。我正在使用片段和DatePickerDialog以獲取日期。每個editText都會有自己的日期。我如何通過datePickerDialog中的日期?我使用onFocusChange如何將DatePickerDialog的值傳遞給不同的editText?
P.S,這樣的對話框彈出時對EDITTEXT用戶點擊。使用setOnClickListener將要求用戶雙擊以顯示datePickerDialog。
FormFragment.java
public class FormFragment extends Fragment {
....
//TODO : Fixed datepicker & time picker
//get Date func
public void showDatePickerDialog(View v) {
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getFragmentManager(), "datePicker");
}
//get time func
public void showTimePickerDialog(View v) {
DialogFragment newFragment = new TimePickerFragment();
newFragment.show(getFragmentManager(), "timePicker");
}
public void onViewCreated(final View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
//get CaseDetailActivity
final Activity activity = this.getActivity();
/*
Use onFocusChangeListener - the dialog automatically popped when clicked on edittext
*/
//inspection date
final View editText_date = activity.findViewById(R.id.input_inspecDateNew);
editText_date.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
//get current text
showDatePickerDialog(v);
}
}
});
//previous inspection date
View editText_prevDate = activity.findViewById(R.id.input_lastInspecDate);
editText_prevDate.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
//get current text
showDatePickerDialog(v);
}
}
});
}
}
DatePickerFragment.java
public class DatePickerFragment extends DialogFragment
implements DatePickerDialog.OnDateSetListener {
public static EditText editText;
@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 getCurrentDate() {
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
String formattedDate = df.format(c.getTime());
editText.setText(formattedDate);
}
public void onDateSet(DatePicker view, int year, int month, int day) {
Calendar c = Calendar.getInstance();
c.set(year, month, day);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String formattedDate = sdf.format(c.getTime());
editText.setText(formattedDate);
}
}
謝謝您的幫助。它像一個魅力。但是這個代碼'editText_date = view.findViewById(R.id.input_inspecDateNew);',必須改爲'editText_date =(EditText)view.findViewById(R.id.input_inspecDateNew);' – xxmilcutexx
歡迎你,你可以使用你想要的東西,只是我舉了一個例子,我們該如何處理它。 –