问题
According to the official Android Dev guide, when the user clicks this button, the system calls the following method:
public void showTimePickerDialog(View v) {
DialogFragment newFragment = new TimePickerFragment();
newFragment.show(getSupportFragmentManager(), "timePicker");
}
However, when I try this in my Fragment Activity, it shows TimePickerFragment
in red. And prompts that TimePickerFragment()
cannot be resolved.
These are my imports related to 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;
When I try this for DatePicker
, the DatePickerFragment
works.
回答1:
You are using getSupportFragmentManager ,So
Do
import android.support.v4.app.DialogFragment;
Don't
import android.app.DialogFragment;
回答2:
You need to extends
TimepickerFragment
asDialogFragment
.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; } }
And try your code like below to create
TimePickerFragment
dialog.public void showTimePickerDialog(View v) { TimePickerFragment newFragment = new TimePickerFragment(); newFragment.show(getSupportFragmentManager(), "timePicker"); }
来源:https://stackoverflow.com/questions/34284389/timepickerfragment-not-working