Showing TimePickerDialog fragment error

后端 未结 3 2003
别那么骄傲
别那么骄傲 2021-01-29 04:21

I am trying to launch a timepicker from a button in a fragment

I\'ve read post regarding the same problems about the Error but the codes doesn\'t match

相关标签:
3条回答
  • 2021-01-29 04:46

    MainActivity cannot be cast to android.app.TimePickerDialog$OnTimeSetListener

    Which means you can not call a method which is declared in the subclass.

    Problem coming form

     android.support.v4.app.DialogFragment timePicker = new TimePickerFragment(); 
    

    Try with

    TimePickerFragment  timePicker = new TimePickerFragment ();
    timePicker.show(getActivity().getSupportFragmentManager(), "time picker");
    

    "Cannot Resolve Method 'getSupportFragmentManager()'"

    Make sure your ROOT Activity extends

    • AppCompatActivity/FragmentActivity

    Did you using ?

    import android.support.v4.app.DialogFragment;
    import android.support.v4.app.Fragment;
    import android.support.v4.app.FragmentManager;
    
    0 讨论(0)
  • 2021-01-29 04:51

    Use getParentFragment() instead of getActivity().

    0 讨论(0)
  • 2021-01-29 05:06

    About the

    MainActivity cannot be cast to android.app.TimePickerDialog$OnTimeSetListener

    it is happening because you are trying to cast your activity to OnTimeSetListener

    return new TimePickerDialog(getActivity(),(TimePickerDialog.OnTimeSetListener) getActivity(), cHour, cMinute, android.text.format.DateFormat.is24HourFormat(getActivity()));
    

    Make sure that your activity is extending the OnTimeSetListener, and if it so, you may try to convert right to your activity

    return new TimePickerDialog(getActivity(),(MainActivity) getActivity(), cHour, cMinute, android.text.format.DateFormat.is24HourFormat(getActivity()));
    

    because your activity will be a instance of OnTimeSetListener.

    Also, I do not recommend using the getActivity() to get the listener from your fragment, its better if you have your listener not attached to your activity.

    0 讨论(0)
提交回复
热议问题