Решение: Определить два интерфейса для пересылки данных из фрагментов в действие.
Шаг 1 .Определите OnDateSetListener
интерфейс для связи между MainActivity
и DatePickerFragment
.
public interface OnDateSetListener {
void onDateSet(String tag, DatePicker view, int year, int month, int dayOfMonth);
}
Шаг 2 .Определите OnTimeSetListener
интерфейс для связи между MainActivity
и TimePickerFragment
.
public interface OnTimeSetListener {
void onTimeSet(String tag, TimePicker view, int hourOfDay, int minute);
}
Шаг 3 .Пусть MainActivity
реализует оба интерфейса.
public class MainActivity extends AppCompatActivity implements OnDateSetListener, OnTimeSetListener {
// Your code her
...
@Override
public void onDateSet(String tag, DatePicker view, int year, int month, int dayOfMonth) {
// Process code with tag here
}
@Override
public void onTimeSet(String tag, TimePicker view, int hourOfDay, int minute) {
// Process code with tag here.
}
}
Шаг 4 .Измените код в DatePickerFragment
public class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {
private static final String ARGUMENT_TAG = "ARGUMENT_TAG";
public static DatePickerFragment newInstance(String tag) {
Bundle args = new Bundle();
args.putString(ARGUMENT_TAG, tag);
DatePickerFragment fragment = new DatePickerFragment();
fragment.setArguments(args);
return fragment;
}
@NonNull
@Override
public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);
return new DatePickerDialog(requireActivity(), this, year, month, day);
}
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
final String tag = getArguments().getString(ARGUMENT_TAG);
OnDateSetListener listener = (OnDateSetListener) requireActivity();
listener.onDateSet(tag, view, year, month, dayOfMonth);
}
}
Шаг 5 .Изменить код в TimePickerFragment
.
public class TimePickerFragment extends DialogFragment implements TimePickerDialog.OnTimeSetListener {
private static final String ARGS_TAG = "ARGS_TAG";
public static TimePickerFragment newInstance(String tag) {
Bundle args = new Bundle();
args.putString(ARGS_TAG, tag);
TimePickerFragment fragment = new TimePickerFragment();
fragment.setArguments(args);
return fragment;
}
@Override
public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
Calendar calendar = Calendar.getInstance();
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);
return new TimePickerDialog(requireActivity(), this, hour, minute, DateFormat.is24HourFormat(getActivity()));
}
@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
final String tag = getArguments().getString(ARGS_TAG);
OnTimeSetListener listener = (OnTimeSetListener) requireActivity();
listener.onTimeSet(tag, view, hourOfDay, minute);
}
}