我正在实现一个扩展DialogFragment的日期选择器。我需要能够在一个Activity(当前工作正常)和一个Fragment(它没有)中实例化该类。
public class DatePickerFragment extends DialogFragment
implements DatePickerDialog.OnDateSetListener {
TheListener listener;
public interface TheListener {
public void returnDate(View v, String date);
}
@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);
listener = (TheListener) getActivity();
// Create a new instance of DatePickerDialog and return it
return new DatePickerDialog(getActivity(), this, year, month, day);
}
public void onDateSet(DatePicker view, int year, int month, int day) {
Calendar c = Calendar.getInstance();
c.set(year, month, day);
Log.i(" DatePickerFragment", " in set date");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String formattedDate = sdf.format(c.getTime());
if (listener != null) {
listener.returnDate(view, formattedDate);
}
}
}
当我尝试从Fragment中实例化日期选择器时,我收到以下运行时错误:
FATAL EXCEPTION: main
Process: com.example.app.debug, PID: 16656
java.lang.ClassCastException: com.example.app.UI.MainActivity cannot be cast to com.example.app.UI.DatePickerFragment$TheListener
at com.example.app.UI.DatePickerFragment.onCreateDialog(DatePickerFragment.java:36)
at android.app.DialogFragment.getLayoutInflater(DialogFragment.java:398)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:890)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1062)
at android.app.BackStackRecord.run(BackStackRecord.java:684)
at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1447)
at android.app.FragmentManagerImpl$1.run(FragmentManager.java:443)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
我知道这个错误是由日期选择器类中的onCreateDialog方法的以下代码行引起的,因为MainActivity对日期选择器一无所知。
listener = (TheListener) getActivity();
调用getActivity()返回"父活动"片段 - 这是MainActivity。这不会实现Listener接口。应用程序中的所有片段都由MainActivity实例化。使用当前代码通过实现Listener接口的单独活动成功实例化日期选择器。
我需要知道的是,如何在Activity和Fragment中使用它?我猜我可以在Main Activity中实例化日期选择器,但我也可能在其他Fragments中需要它,所以这种方式可能会变得混乱。另一种方法是修复监听器,以便可以从Fragment内部触发,但我不确定如何。关于如何最好地解决这个问题的任何建议?