TimePickerFragment不起作用

时间:2015-12-15 08:37:53

标签: android android-dialogfragment timepicker

根据官方Android Dev guide,当用户点击此按钮时,系统会调用以下方法:

public void showTimePickerDialog(View v) {
    DialogFragment newFragment = new TimePickerFragment();
    newFragment.show(getSupportFragmentManager(), "timePicker");
}

但是,当我在片段活动中尝试此操作时,它会以红色显示TimePickerFragment。并提示TimePickerFragment()无法解决。

这些是与TimePicker相关的导入:

import android.app.AlarmManager;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.Dialog;
import android.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.view.View.OnClickListener;
import android.widget.DatePicker;
import android.widget.TimePicker;
import android.app.TimePickerDialog;

当我为DatePicker尝试此操作时,DatePickerFragment可以正常工作。

2 个答案:

答案 0 :(得分:2)

您正在使用 getSupportFragmentManager ,所以

<强>不要

import android.support.v4.app.DialogFragment;

<强>唐&#39;吨

import android.app.DialogFragment;

答案 1 :(得分:1)

  • 您需要将TimepickerFragment扩展为DialogFragment

    public class TimepickerFragment extends DialogFragment{
    
    public TimepickerFragment(){
    
    }       
    private TimePickerDialog.OnTimeSetListener callback = new TimePickerDialog.OnTimeSetListener() {
    
    @Override
    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {         
       Log.i("Selected Time - ",  hourOfDay + ":" + minute);
    
    }
    };
    
    public Dialog onCreateDialog(Bundle bundle){
    int hourOfDay = 01;
    int minute = 01;
    boolean is24HourView = false;
    TimePickerDialog timePickerDialog = new TimePickerDialog(getActivity(), callback, hourOfDay, minute, is24HourView); 
    return timePickerDialog;
    }
    }
    
  • 然后尝试使用以下代码创建TimePickerFragment对话框。

     public void showTimePickerDialog(View v) {
      TimePickerFragment newFragment = new TimePickerFragment();
      newFragment.show(getSupportFragmentManager(), "timePicker");
    }