Search code examples
androidandroid-fragmentsradio-buttonradio-grouponcheckedchanged

android - Radio Buttons in a Fragment causing crash


This crashes when the fragment has launched. Could it be in the radio-button code?

    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

Solution

  • You need to inflate the views first.

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

    getView() returns null until you have returned a view hierarchy from onCreateView(), so you should not be calling getView() inside that method.