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_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










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


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

Query/Feedback


Your Email Id  
 
Subject 
 
Query/FeedbackCharacters remaining 250