java - DialogFragments 中的空指针异常,android

标签 java android dialog onclick nullpointerexception

这是我的代码 fragment :

public class ChooseNumWorkoutsDialog extends DialogFragment implements OnClickListener {
    Button btnClose, btnFinished;
    NumberPicker np;

    public ChooseNumWorkoutsDialog() {
        // Empty constructor required for DialogFragment
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.dialog_numpicker, container);
        getDialog().setTitle("Number of Exercises");
        btnClose = (Button) findViewById(R.id.btnClose);
        btnFinished = (Button) findViewById(R.id.btnFinished);
        np = (NumberPicker) findViewById(R.id.np);
        //np.setMaxValue(20);
        //np.setMinValue(1);
        //np.setWrapSelectorWheel(false);
        //btnClose.setOnClickListener(this);
        //btnFinished.setOnClickListener(this);   
        return view;
    }

XML 文件确实包含所有引用的按钮和数字选择器。运行时,在“np.setMaxValue(20);”处发现一个空指针异常,我让它工作的唯一方法是注释掉你看到的所有注释掉的部分。

  • 是否有一些我不知道的规则表明我不能在 dialogfragment 中设置我的 onclick 监听器等?
  • 解决这个问题的最佳方法是什么?

最佳答案

onActivityCreated() 中初始化您的 View .来自文档:

Called when the fragment's activity has been created and this fragment's view hierarchy instantiated. It can be used to do final initialization once these pieces are in place, such as retrieving views or restoring state. It is also useful for fragments that use setRetainInstance(boolean) to retain their instance, as this callback tells the fragment when it is fully associated with the new activity instance. This is called after onCreateView(LayoutInflater, ViewGroup, Bundle) and before onStart().

你可以调用getView().findViewById(R.id.np);

或使用 np = (NumberPicker) view.findViewById(R.id.np);onCreateView() ,请注意“ View 。

关于java - DialogFragments 中的空指针异常,android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11491913/

相关文章:

javascript - JQuery UI 对话框重新加载原始内容

android - 如何将动态加载的类转换为它的接口(interface)?

java - 按升序将数据存储在表中

java - 访客模式的实现

android - 使用 IBM Watson Android sdk 将音频文件写入 websocket

Android map NullPointerException ItemizedOverlay

android - 需要语音识别没有谷歌对话框

java - 限制 JTable 中的列宽,但保留扩展列的能力

java - Android - 中国生肖应用程序 - 如何攻击这个

android - 在android应用程序中合并两个手势原始文件