Can I implement
TimePickerDialog.OnTimeSetListener
in a Fragment class?
if it is possible HOW?
this is my TimePickerFragment.class
public class TimePickerFragment extends DialogFragment {
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Calendar c = Calendar.getInstance();
int cHour = c.get(Calendar.HOUR_OF_DAY);
int cMinute = c.get(Calendar.MINUTE);
return new TimePickerDialog(getActivity(), (TimePickerDialog.OnTimeSetListener) getActivity(), cHour, cMinute, android.text.format.DateFormat.is24HourFormat(getActivity()));
}
}
do I need to modify this code so i can use it in a Fragment class?
this is where i want to implement it
public class BluetoothFragment extends Fragment
i have already tried it but i'm getting this error
java.lang.ClassCastException: com.example.android.bluetoothplantdroid.MainActivity cannot be cast to android.app.TimePickerDialog$OnTimeSetListener
You can set Listener to your DialogFragment to get a callback in origin fragment
public class TimePickerFragment extends DialogFragment {
public static TimePickerFragment newInstance() {
return new TimePickerFragment();
}
private TimePickerDialog.OnTimeSetListener listener;
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Calendar c = Calendar.getInstance();
int cHour = c.get(Calendar.HOUR_OF_DAY);
int cMinute = c.get(Calendar.MINUTE);
return new TimePickerDialog(getActivity(), listener, cHour, cMinute,
android.text.format.DateFormat.is24HourFormat(getActivity()));
}
public void setListener(TimePickerDialog.OnTimeSetListener listener) {
this.listener = listener;
}
}
This is how you can get a callback in origin fragment -
public class MyFragment extends Fragment implements TimePickerDialog.OnTimeSetListener {
May be click event of some widget... {
TimePickerFragment.newInstance().setListener(this);
// Show your dialog
}
@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
// data when time has been set.
}
}
Follow below Code : Pass Activity or Fragment context .
public static void setTimeFromTimePicker(Context context, EditText editText) {
int hourOfDay, minute;
final Calendar c = Calendar.getInstance();
hourOfDay = c.get(Calendar.HOUR_OF_DAY);
minute = c.get(Calendar.MINUTE);
TimePickerDialog dpd = new TimePickerDialog(context, (timePicker, hourOfDay1, minute1) -> {
Time time = new Time(hourOfDay1, minute1, 0);
SimpleDateFormat simpleDateFormat = new
SimpleDateFormat("hh:mm aa", Locale.getDefault());
String s = simpleDateFormat.format(time);
editText.setText(s);
}, hourOfDay, minute, false);
dpd.show();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With