Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting spinners in fragment

I am trying to set the values for my spinner from a string Array in one of my fragments in the onCreateView in my public final class Manual extends Fragment:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View v = inflater.inflate(R.layout.manual, container, false);

    String [] values = 
        {"Time at Residence","Under 6 months","6-12 months","1-2 years","2-4 years","4-8 years","8-15 years","Over 15 years",};
    Spinner spinner = (Spinner) v.findViewById(R.id.spinner1);
    ArrayAdapter<String> LTRadapter = new ArrayAdapter<String>(this.getActivity(), android.R.layout.simple_spinner_item, values);
    LTRadapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
    spinner.setAdapter(LTRadapter);

    return inflater.inflate(R.layout.manual, container, false);

}

I get no errors with my code, however it doesn't set the spinner. The spinner remains blank with no values. Any ideas on why my code isn't setting the spinner?

like image 481
Nick Avatar asked Sep 02 '12 17:09

Nick


People also ask

What is a spinner in Android?

Spinners provide a quick way to select one value from a set. In the default state, a spinner shows its currently selected value. Touching the spinner displays a dropdown menu with all other available values, from which the user can select a new one. You can add a spinner to your layout with the Spinner object.


1 Answers

The problem was I was returning a new view, not the one I set. I had to return v; and it worked fine.

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View v = inflater.inflate(R.layout.manual, container, false);

    String [] values = 
        {"Time at Residence","Under 6 months","6-12 months","1-2 years","2-4 years","4-8 years","8-15 years","Over 15 years",};
    Spinner spinner = (Spinner) v.findViewById(R.id.spinner1);
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this.getActivity(), android.R.layout.simple_spinner_item, values);
    adapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
    spinner.setAdapter(adapter);

    return v;

}
like image 199
Nick Avatar answered Nov 12 '22 00:11

Nick