51
package org.example.mbtiapplication;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;

public class MBTITest extends Activity implements OnItemSelectedListener  {

    private Spinner firstSpinner;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mbtitest);

        Spinner firstSpinner = (Spinner) findViewById(R.id.spinner1);
        // Create an ArrayAdapter using the string array and a default spinner layout
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
                R.array.spinnerarraybool, android.R.layout.simple_spinner_item);
        // Specify the layout to use when the list of choices appears
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        // Apply the adapter to the spinner
        firstSpinner.setAdapter(adapter);
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View v, int position,
            long id) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onNothingSelected(AdapterView<?> arg0) {
        // TODO Auto-generated method stub      
    } 
}

XML Layout:

<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <TableRow
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <TextView
            android:layout_width="120dp"
            android:layout_height="match_parent"
            android:layout_marginLeft="5dp"
            android:gravity="center_vertical"
            android:text="I like to go out more than staying home." />

        <Spinner
            android:id="@+id/spinner1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </TableRow>

    <TableRow
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <TextView
            android:layout_width="120dp"
            android:layout_height="match_parent"
            android:layout_marginLeft="5dp"
            android:gravity="center_vertical"
            android:textSize="10.5dp"
            android:text="Sensing v Intuition" />

        <Spinner
            android:id="@+id/spinner2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </TableRow>
</TableLayout>

I'm a new Android programmer and having trouble with using Spinner, i've tried multiple tutorials and still am confused. I'd like to know what my next step is here, as far as I know I have set up my spinner in XML, in Java I have identified that spinner, created an ArrayAdapter for said spinner, and specified some options. I'm not to sure if I have populated the spinner yet or how to manuever with the spinner object. I'd like to be able to use the spinner object to select one of three options and then keep that value inside of the textview inside of the spinner.

Pratik Butani
  • 60,504
  • 58
  • 273
  • 437

7 Answers7

62

You're almost there. As you can see, the onItemSelected will give you a position parameter, you can use this to retrieve the object from your adapter, as in getItemAtPosition(position).

Example:

spinner.setOnItemSelectedListener(this);

...

public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
    Toast.makeText(parent.getContext(), 
        "OnItemSelectedListener : " + parent.getItemAtPosition(pos).toString(),
        Toast.LENGTH_SHORT).show();
}

This will put a message on screen, with the selected item printed by its toString() method.

Pratik Butani
  • 60,504
  • 58
  • 273
  • 437
bgse
  • 8,237
  • 2
  • 37
  • 39
  • 2
    Would you show me an example? This has been kicking my arse for the past hours. – Joseph Little-Indelible Nov 22 '13 at 18:13
  • 1
    Just caught that you are also missing "spinner.setOnItemSelectedListener(this)" :) – bgse Nov 22 '13 at 18:25
  • 1
    Where does "spinner.setOnItemSelectedListener(this)" belong? – Joseph Little-Indelible Nov 22 '13 at 18:58
  • @JosephLittle-Indelible The spinner.setOnItemSelectedListener(this) where this is the interface instance belongs to the interface OnItemSelectedListener implemented in your activtity. At documentation [ http://developer.android.com/intl/es/guide/topics/ui/controls/spinner.html ] – Asha Mar 05 '16 at 09:35
  • OP asked for code to "keep that value inside of the textview inside of the spinner". This answer does not appear to do that when I paste it into my code. It shows a toast but the spinner remains blank. Am I missing something? – dinosaur May 09 '16 at 05:20
  • Why doesn't use parent.getSelectedItem().toString() ? – Plugie Jan 28 '18 at 14:12
32

If you don't want to implement the listener, you can set it up like this directly where you want it (call on your spinner after your adapter has been set):

spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                switch (position) {
                    case 0:
                        Toast.makeText(parent.getContext(), "Spinner item 1!", Toast.LENGTH_SHORT).show();
                        break;
                    case 1:
                        Toast.makeText(parent.getContext(), "Spinner item 2!", Toast.LENGTH_SHORT).show();
                        break;
                    case 2:
                        Toast.makeText(parent.getContext(), "Spinner item 3!", Toast.LENGTH_SHORT).show();
                        break;
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

               // sometimes you need nothing here
            }
        });
Azurespot
  • 3,066
  • 3
  • 45
  • 73
23

Another thing: When you have more than one spinner in your layout, you have to implement a switch selection in the onItemSlected() method to know which widget was clicked. Something like this:

@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
    switch (parent.getId()){
        case R.id.sp_alarmSelection:
            //Do something
            Toast.makeText(this, "Alarm Selected: " + parent.getSelectedItem().toString(), Toast.LENGTH_SHORT).show();
            break;
        case R.id.sp_optionSelection:
            //Do another thing 
            Toast.makeText(this, "Option Selected: " + parent.getSelectedItem().toString(), Toast.LENGTH_SHORT).show();
            break;
    }
}
Jorge Torres
  • 1,806
  • 1
  • 11
  • 6
14

For Kotlin and bindings the code is:

binding.spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener{
            override fun onNothingSelected(parent: AdapterView<*>?) {
            }

            override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
            }
        }
Ilja Popov
  • 1,091
  • 8
  • 8
2

Joseph: spinner.setOnItemSelectedListener(this) should be below Spinner firstSpinner = (Spinner) findViewById(R.id.spinner1); on onCreate

antonio
  • 18,044
  • 4
  • 45
  • 61
Tuan Do
  • 21
  • 1
1

I think this will benefit you Try this I'm using to change the language in my application

String[] districts;
Spinner sp;

......

 sp = (Spinner) findViewById(R.id.sp);
         districts = getResources().getStringArray(R.array.lang_array);
         ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,districts);
         sp.setAdapter(adapter);
         sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
              @Override
             public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long arg3) {
                  // TODO Auto-generated method stub
                  int index = arg0.getSelectedItemPosition();
                  Toast.makeText(getBaseContext(), "You select "+districts[index]+" id "+position, Toast.LENGTH_LONG).show();
                  switch(position){
                      case 0:
                          setLocal("fr");
                          //recreate();
                          break;
                      case 1:
                          setLocal("ar");
                          //recreate();
                          break;
                      case 2:
                          setLocal("en");
                          //recreate();
                          break;
                      default: //For all other cases, do this
                          setLocal("en");
                          //recreate();
                          break;
                  }
              }
             @Override
            public void onNothingSelected(AdapterView<?> arg0) {
                   // TODO Auto-generated method stub
                         }
        });

and this is my String Array

<string-array name="lang_array">
    <item>french</item>
    <item>arabic</item>
    <item>english</item>
</string-array>
Said Erraoudy
  • 1,490
  • 1
  • 13
  • 21
0
spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

               //check if spinner2 has a selected item and show the value in edittext

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

               // sometimes you need nothing here
            }
        });

spinner2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

               //check if spinner1 has a selected item and show the value in edittext


            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

               // sometimes you need nothing here
            }
        });
Rohit Sharma
  • 1,384
  • 12
  • 19