为什么我在 android 4.0.3 中出现 TimePicker NullPointerException?

Why am I getting TimePicker NullPointerException in android 4.0.3?

我有这个 class,它显示了一个间隔为 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 上完美运行,但是当我 运行 它在模拟器或真实设备上 运行ning android 4.0.3 它抛出以下异常:

java.lang.NullPointerException 关于这一行:ViewGroup layout = (ViewGroup) tpLayout.getChildAt(0);

错误很明显,但我看不到布局组件 ID,因为 Device monitor 中的屏幕捕获在 API 15.

中不受支持

可以推一下吗?为什么我会收到此错误?我缺少什么布局 ID?我很确定许多开发人员都面临着同样的问题。我知道我在这里遗漏了一个非常小的部分,但我无法发现它。

其实问题出在这里:

int tpLayoutId = getResources().getIdentifier("timePickerLayout", "id", "android");

API-15.

中没有名称为 timePickerLayout 的内部标识符可用

因此 tpLayoutId0 这使得您的 tpLayout 等于 null;并在空对象上调用方法抛出 NullPointerException.

建议:不要依赖 android 的内部资源声明,因为它们被设为私有是有原因的。