Reputation: 31
The spinner doesn't work. It didn't use to show arrow when I was just playing with it in design mode, it's not showing text after I implemented it with some code somehow.
<Spinner
android:id="@+id/spinner"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
Spinner spinner;
ArrayList spinnerArrayList;
ArrayAdapter spinnerAdapter;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinner = findViewById(R.id.spinner);
spinnerArrayList = new ArrayList();
spinnerAdapter = new ArrayAdapter(this,android.R.layout.simple_spinner_item,spinnerArrayList);
spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(spinnerAdapter);
spinnerArrayList.add("Guitar");
spinnerArrayList.add("Drums");
spinnerArrayList.add("Keyboard");
}
Upvotes: 3
Views: 210
Reputation: 140
There is no need to create ArrayAdapter
to populate your spinner if the list you want to insert is static.
I recommend using a way easier and direct method to avoid this hassle.
In strings.xml:
<string-array name="list_spinner">
<item>Guitar</item>
<item>Drums</item>
<item>Keyboard</item>
</string-array>
In the layout that contains your spinner:
<Spinner
android:id="@+id/spinner"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:entries="@array/list_spinner"
/>
And You're Done!
EXTRA:
If you want to make your spinner responsive to item selection in your spinner, add this code to the corresponding .java file of the layout containing the spinner in the onCreate()
method:
final Spinner spin=findViewById(R.id.spinner);
spin.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
String item_name=spin.getSelectedItem().toString();
Log.e("Selected item : ",item_name);
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
Upvotes: 1
Reputation: 416
What you are doing is you are changing your ArrayList after setting up the adapter. So adapter doesn't know that the data is changed.
You can solve this in 2 ways :
Add elements in the ArrayList before setting up the adapter
Use notifyDataSetChanged() at the end of the code or whenever you change the ArrayList
Like this : spinnerAdapter.notifyDataSetChanged()
Upvotes: 3