문제

I want to develop simple alarm application using timePickerDialog. The problem is the constructor TimePickerDialog is undefined on extends fragment.

What should I do? Any suggestions ?

Please help me. Thank you for your concern.

Here is part of the code.

   public class ReminderFragment extends Fragment {

   @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View v = inflater.inflate(R.layout.fragment_reminder, container, false);

    textAlarmPrompt = (TextView) v.findViewById(R.id.alarmprompt);

    buttonstartSetDialog = (Button) v.findViewById(R.id.startSetDialog);
    buttonstartSetDialog.setOnClickListener(new OnClickListener(){

        @Override
        public void onClick(View v) {
            textAlarmPrompt.setText("");
            openTimePickerDialog(false);

        }});
     return v;
   }

   private void openTimePickerDialog(boolean is24r){
    Calendar calendar = Calendar.getInstance();

    timePickerDialog = new TimePickerDialog(
            ReminderFragment.this, 
            onTimeSetListener, 
            calendar.get(Calendar.HOUR_OF_DAY), 
            calendar.get(Calendar.MINUTE), 
            is24r);
    timePickerDialog.setTitle("Set Alarm Time");  

    timePickerDialog.show();

        }

     OnTimeSetListener onTimeSetListener= new OnTimeSetListener(){

    @Override
    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {

        Calendar calNow = Calendar.getInstance();
        Calendar calSet = (Calendar) calNow.clone();

        calSet.set(Calendar.HOUR_OF_DAY, hourOfDay);
        calSet.set(Calendar.MINUTE, minute);
        calSet.set(Calendar.SECOND, 0);
        calSet.set(Calendar.MILLISECOND, 0);

        if(calSet.compareTo(calNow) <= 0){
            //Today Set time passed, count to tomorrow
            calSet.add(Calendar.DATE, 1);
        }

        setAlarm(calSet);
    }};
   }
도움이 되었습니까?

해결책

Use getActivity() instead of this ReminderFragment.this. The first param is a context ReminderFragment.this refers to the ReminderFragment. getActivity() returns the Activity this Fragment is associated with.

 timePickerDialog = new TimePickerDialog(
        getActivity(), 
        onTimeSetListener, 
        calendar.get(Calendar.HOUR_OF_DAY), 
        calendar.get(Calendar.MINUTE), 
        is24r);

다른 팁

A Fragment is not a valid Context. Use getActivity() instead.

timePickerDialog = new TimePickerDialog(
    getActivity(), 
    onTimeSetListener, 
    calendar.get(Calendar.HOUR_OF_DAY), 
    calendar.get(Calendar.MINUTE), 
    is24r);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top