我目前正在將活動轉換爲片段。該活動包含一個Edittext,單擊時顯示一個用於選擇日期的DialogFragmment。在活動中,我會簡單地調用它來顯示對話框:在片段中顯示DialogFragment
@SuppressLint("NewApi")
public void showDatePickerDialog(View v) {
DatePickerFragment newFragment = new DatePickerFragment(datePickerEditText);
newFragment.show(getFragmentManager(), "datePicker");
}
但是,這似乎不工作,以顯示從片段的對話框。我在「show」方法中出現錯誤。所以要清楚,我想知道如何從片段中顯示DialogFragment?
這是DialogFragment
public class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {
public EditText activity_edittext;
@SuppressLint("ValidFragment")
public DatePickerFragment(EditText edit_text) {
activity_edittext = edit_text;
}
@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);
return new DatePickerDialog(getActivity(), this, year, month, day);
}
@Override
public void onDateSet(DatePicker view, int year, int month, int day) {
activity_edittext.setText(String.valueOf(day) + "/" + String.valueOf(month + 1) + "/" + String.valueOf(year));
}
}
工程很棒。非常感謝。 – mgnusl
@mgnusl不客氣!我很樂意幫助你。 – mari