gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 03:44:49 25 4
gpt4 key购买 nike

这是我的代码 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com