【问题标题】:android - Radio Buttons in a Fragment causing crashandroid - 片段中的单选按钮导致崩溃
【发布时间】:2017-05-28 07:14:57
【问题描述】:

片段启动时会崩溃。可以在单选按钮代码中吗?

    RadioGroup q1;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        q1 = (RadioGroup) getView().findViewById(R.id.radioGQ1);
        q1.setOnCheckedChangeListener(this);
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_exercise, container, false);

    }
    rest -> http://pastebin.com/cRptSmD4

【问题讨论】:

    标签: android android-fragments radio-button radio-group oncheckedchanged


    【解决方案1】:

    您需要先膨胀视图。

    View root = inflater.inflate(R.layout.fragment_exercise, container, false);
    q1 = (RadioGroup) root.findViewById(R.id.radioGQ1);
    q1.setOnCheckedChangeListener(this);
    return root;
    

    getView() 在您从 onCreateView() 返回视图层次结构之前返回 null,因此您不应在该方法内调用 getView()

    【讨论】:

      【解决方案2】:

      FragmentContextgetActivity,如果你没有初始化任何视图,使用getActivity()。所以在你的代码中:

      替换这个:

      q1 = (RadioGroup) getView().findViewById(R.id.radioGQ1);
      

      使用此代码:

      q1 = (RadioGroup) getActivity().findViewById(R.id.radioGQ1);
      

      【讨论】:

        猜你喜欢
        • 2013-11-03
        • 2020-03-05
        • 2015-04-23
        • 1970-01-01
        • 1970-01-01
        • 2020-05-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多