2012-07-15 105 views
1

这里是我的代码片段:空指针异常,安卓

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文件没有包含所有被引用的按钮和numberPickers。运行此操作时,会在“np.setMaxValue(20);”处找到空指针异常,但我可以使其工作的唯一方法是将注释掉的所有注释部分注释掉。

  • 是否有一些规则,我不知道那种状态我不能在对话框片段中设置我的onclick监听器等?
  • 解决此问题的最佳方法是什么?

回答

4

onActivityCreated()中初始化您的视图。从技术文档:

当片段的活动已创建这 片段的视图层次实例调用。一旦这些部分到位,它可以用于执行最终的初始化 ,例如检索 视图或恢复状态。对于使用setRetainInstance(boolean)来保留其实例的片段也很有用,因为此回调告知片段何时与新活动 实例完全关联。这是在onCreateView(LayoutInflater,ViewGroup, Bundle)和onStart()之前调用的。

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

onCreateView()使用np = (NumberPicker) view.findViewById(R.id.np);,注意到 “视图。

+0

完美,正是我一直在寻找:)谢谢! – Ali 2012-07-15 12:47:23