Articles → Android → Spinner Control In Android
Spinner Control In Android
What Is A Spinner Control?
Bind Dropdown Using Adapter
Click to Enlarge
String fruitlist[] = {
"apple",
"banana",
"orange",
"cherry"
};
Spinner spinner = (Spinner) findViewById(R.id.spinner);
ArrayAdapter < String > adapter = new ArrayAdapter < String > (this, R.layout.support_simple_spinner_dropdown_item, fruitlist);
spinner.setAdapter(adapter);
Click to Enlarge
Spinner spinner = (Spinner) findViewById(R.id.spinner);
ArrayAdapter < CharSequence > adapter = ArrayAdapter.createFromResource(this, R.array.sample_array, android.R.layout.simple_spinner_item);
spinner.setAdapter(adapter);
<?xml version="1.0" encoding="utf-8"?>
<TextView
android:id="@+id/textView2"
android:layout_tooltip="Picture showing " width="match_parent"
android:layout_height="wrap_content"
xmlns:android="http://schemas.android.com/apk/res/android" />
String fruitlist[] = {
"apple",
"banana",
"orange",
"cherry"
};
Spinner spinner = (Spinner) findViewById(R.id.spinner);
ArrayAdapter < CharSequence > adapter = ArrayAdapter.createFromResource(this, R.array.sample_array, R.layout.mylist);
spinner.setAdapter(adapter);
Onselected Event In Spinner
- Create a new class and implement AdapterView.OnItemSelectedListener
- Implement onItemSelected and onNothingSelected method
package com.example.demo_application;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Toast;
import androidx.appcompat.widget.AppCompatSpinner;
public class myOnItemSelectedListener implements AdapterView.OnItemSelectedListener {
@Override
public void onItemSelected(AdapterView < ? > adapterView, View view, int i, long l) {
AppCompatSpinner spinner = (AppCompatSpinner) view.getParent();
Toast.makeText(spinner.getContext(), spinner.getSelectedItem().toString(), Toast.LENGTH_LONG).show();
}
@Override
public void onNothingSelected(AdapterView < ? > adapterView) {}
}
Spinner spinner = (Spinner) findViewById(R.id.spinner);
ArrayAdapter < CharSequence > adapter = ArrayAdapter.createFromResource(this, R.array.sample_array, android.R.layout.simple_spinner_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new myOnItemSelectedListener());
Click to Enlarge