ciberelfo ciberelfo - 2 months ago 17
Android Question

Spinner shows empty when use fragment

I have a spinner in normal activity and a wants to try to use spinner in fragment but in the fragment, shows empty when run it
example

My code in onCreateView

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

View vista =inflater.inflate(R.layout.fragment_pag1,container,false);



calcular= (Button)vista.findViewById(R.id.button);
etd=(EditText)vista.findViewById(R.id.editText);
resultadocp=(TextView)vista.findViewById(R.id.textView3);
lista = (Spinner)vista.findViewById(R.id.spinner);

String []opciones={"one","two","three","four","five"};

ArrayAdapter adapter = new ArrayAdapter(getActivity(),android.R.layout.simple_list_item_1, opciones);
lista.setAdapter(adapter); return vista; }

Answer

Example one:

You can use this

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this.getActivity(), android.R.layout.simple_spinner_item, opciones);
adapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
lista.setAdapter(adapter);

`Insted of

ArrayAdapter adapter = new ArrayAdapter(getActivity(),android.R.layout.simple_list_item_1, opciones);
lista.setAdapter(adapter);

Example two:

Create spinner xml

<Spinner
android:id="@+id/spinner"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />

Add your spinner string to string.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="string_array">
    <item>one</item>
    <item>two</item>
    <item>three</item>
    <item>four</item>
    <item>five</item>
</string-array>

Add this code to your fragment

Spinner spinner = (Spinner)lista.findViewById(R.id.spinner);

ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this.getActivity(),
    R.array.string_array, android.R.layout.simple_spinner_item);

 adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);

just try this... I hope it works for you...

Comments