Articles → Android → Spinner Control In Android

Spinner Control In Android






What Is A Spinner Control?





Bind Dropdown Using Adapter




Picture showing the spinner control inside the linear layout
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);




Picture showing the output of Spinner control in android
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




  1. Create a new class and implement AdapterView.OnItemSelectedListener
  2. 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());




Picture showing the output of OnSelected event in spinner
Click to Enlarge


Posted By  -  Karan Gupta
 
Posted On  -  Saturday, November 2, 2019

Query/Feedback


Your Email Id
 
Subject
 
Query/FeedbackCharacters remaining 250