我有这个课程,它显示一个间隔为10分钟的时间选择器:
public class TimePickerFragment extends DialogFragment
implements TimePickerDialog.OnTimeSetListener {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
// Convert current minutes to tens
// 55 = 50, 56 = 00
int minute = c.get(Calendar.MINUTE) / 10;
minute = (minute > 5) ? 0 : minute;
final TimePickerDialog tpd = new TimePickerDialog(getActivity(), this, hour, minute,
DateFormat.is24HourFormat(getActivity()));
tpd.setOnShowListener(new DialogInterface.OnShowListener() {
@Override
public void onShow(DialogInterface dialog) {
int tpLayoutId = getResources().getIdentifier("timePickerLayout", "id", "android");
ViewGroup tpLayout = (ViewGroup) tpd.findViewById(tpLayoutId);
ViewGroup layout = (ViewGroup) tpLayout.getChildAt(0);
// Customize minute NumberPicker
NumberPicker minutePicker = (NumberPicker) layout.getChildAt(2);
minutePicker.setDisplayedValues(new String[]{"00", "10", "20", "30", "40", "50"});
minutePicker.setMinValue(0);
minutePicker.setMaxValue(5);
}
});
return tpd;
}
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
minute = minute * 10;
// Do something with the time chosen by the user
final String selectedDate = String.valueOf(hourOfDay) + ":" + String.valueOf(minute);
EditText selectedTimeTxt = (EditText) getActivity().findViewById(R.id.selectedTime);
selectedTimeTxt.setText(selectedDate);
}
}
代码完全适用于android Lollipop
,但是当我在模拟器上运行它,或运行android 4.0.3
的真实设备时,它会引发以下异常:
java.lang.NullPointerException
关于此行:ViewGroup layout = (ViewGroup) tpLayout.getChildAt(0);
错误不仅仅是明确的,但我无法看到布局组件ID,因为API 15中不支持Device monitor
中的屏幕捕获。
答案 0 :(得分:2)
实际上问题在于:
int tpLayoutId = getResources().getIdentifier("timePickerLayout", "id", "android");
API-15 中没有名称为timePickerLayout
的内部标识符。
因此tpLayoutId
为0
,这使tpLayout
等于null
;并在null对象上调用方法抛出NullPointerException
。
建议:不要依赖于android的内部资源声明,因为这是他们被私有化的原因。