Error populating spinner in a fragment

前端 未结 1 512
长情又很酷
长情又很酷 2020-12-21 10:28

I have a Activity with two fragments. One of them hava a spinner. When I populate it the app crashes. I don\'t know why. In android developers it\'s confused how do it in f

相关标签:
1条回答
  • 2020-12-21 11:07

    I had the same problem where my app crashed when populating a spinner. In my case, the spinner I was populating was defined in the fragment's XML file, so the trick was getting findViewById() to find it. I see in your case you tried to use getActivity():

    sp = (Spinner) getActivity().findViewById(R.id.spinner1);
    

    I also tried using both getActivity() and getView(), and both caused crashes (null spinner, and NULL Pointer exception respectively).

    I finally got this to work by replacing getActivity() with the fragment's view. I did this by populating the spinner when onCreateView() is called. Here are some snippets from my final code:

    private Spinner spinner;
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
    {
      View view = inflater.inflate(R.layout.myFragmentXmlFile, container, false);
      // Now use the above view to populate the spinner.
      setSpinnerContent( view );
      ...
    }
    
    private void setSpinnerContent( View view )
    {
      spinner = (Spinner) view.findViewById( R.id.mySpinner );
      ...
      spinner.setAdapter( adapter );
      ...
    }
    

    So I passed the fragment view into my function and referenced that view to configure the spinner. That worked perfectly. (And quick disclaimer - I'm new to Android myself, so perhaps some of the above terminology can be corrected or clarified if needed by more experienced people.)

    Hope it helps!

    0 讨论(0)
提交回复
热议问题