我正在尝试从片段开始时间选择器片段并在那里接收结果。
public class DataFragment extends Fragment implements TimePickerDialog.OnTimeSetListener{
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//code
setTodayBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
DialogFragment newFragment = new TimePickerFragment();
newFragment.show(getFragmentManager(), "timePicker");
}
});
//code
}
@Override
public void onTimeSet(TimePicker timePicker, int i, int i1) {
//get info here
}
}
TimePickerFragment:
public class TimePickerFragment extends DialogFragment {
private TimePickerDialog.OnTimeSetListener mListener;
private Context context;
@Override
public void onAttach(Context context) {
super.onAttach(context);
this.context = context;
try {
mListener = (TimePickerDialog.OnTimeSetListener) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString() + " must implement OnTimeSetListener");
}
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
return new TimePickerDialog(context, mListener, hour, minute, DateFormat.is24HourFormat(context));
}
}
我明白了:
java.lang.ClassCastException: michlind.com.workcalendar.views.MainActivity@b61773f must implement OnTimeSetListener
at ---.com.workcalendar.views.TimePickerFragment.onAttach(TimePickerFragment.java:30)
答案 0 :(得分:1)
将TimePickerFragment更改为如下所示:
public class TimePickerFragment extends DialogFragment {
private TimePickerDialog.OnTimeSetListener mListener;
private Context context;
public void setListener(TimePickerDialog.OnTimeSetListener mListener) {
this.mListener = mListener;
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
this.context = context;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
return new TimePickerDialog(context, mListener, hour, minute, DateFormat.is24HourFormat(context));
}
}
现在修改你的DataFragment类 -
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//code
setTodayBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
TimePickerFragment newFragment = new TimePickerFragment();
newFragment.setListener(this);
newFragment.show(getFragmentManager(), "timePicker");
}
});
//code
}