12

I want to set the spinner to show the name country even if any other list is selected. I have used a textview which displays the selected item of the Spinner List. As I used the setselection method to set the spinner title to Country the EditText also eventually changes. I went through various topic answered regarding this but couldn't find suitable response

I am attaching my code below

MainActivity.java

package com.example.spinner;

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

public class MainActivity extends Activity {

    Spinner sp;
    TextView t;
    String[] country;
    int sp_position;
    String selected;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        String myString = "Country"; 

        sp = (Spinner)findViewById(R.id.spinner1);
        t = (TextView)findViewById(R.id.textView1);
        country = getResources().getStringArray(R.array.spinner);
        ArrayAdapter<String> ad = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_dropdown_item,country);   
        sp_position = ad.getPosition(myString);
        sp.setAdapter(ad);
        ad.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        sp.setOnItemSelectedListener(new OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> arg0, View arg1,
                    int arg2, long arg3) {
                selected = sp.getSelectedItem().toString();
                System.out.println(selected);
                setid();

            }

            private void setid() {
                sp.setSelection(sp_position);


            }

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

            }
        });

        t.setText(selected);

    }




    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}

My XML file

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="48dp"
        android:layout_marginTop="69dp"
        android:maxLines="4"
        android:hint="Address" />

    <Spinner
        android:id="@+id/spinner1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignRight="@+id/textView1"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="72dp" 
        />

</RelativeLayout>

My STRINGS.XML

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">Spinner</string>
    <string name="action_settings">Settings</string>
    <string name="hello_world">Hello world!</string>
    <string-array name="spinner">
        <item>Country</item>
        <item>India</item>
        <item>Russia</item>
        <item>USA</item>
        <item>France</item>
        <item>United Kingdom</item>
    </string-array>
<string name ="Country">Country</string>
</resources>

My Requirement is whatever is selected in the spinner the Textview should display the selected Item but The spinner should always show the first item or in my case Country

Saraschandraa
  • 478
  • 1
  • 10
  • 28
  • What do you want exactly? Give an example. – Jitender Dev Nov 13 '13 at 05:18
  • Say there is a Spinner which contains the list of countries and a textview. Initially the spinner has a header named Country and after selecting the list in the spinner the Textview should get the value of the item selected on the spinner but the spinner should still display its default title i.e Country – Saraschandraa Nov 13 '13 at 05:22
  • Ok got it, You want this http://stackoverflow.com/questions/867518/how-to-make-an-android-spinner-with-initial-text-select-one – Jitender Dev Nov 13 '13 at 05:25
  • Also go through this http://www.mkyong.com/android/android-spinner-drop-down-list-example/ – Jitender Dev Nov 13 '13 at 05:28
  • No this example shows another drop down list nested in one. My question is after selecting a value in the spinner the selected value should be displayed in Textview and the spinner should set to initial value – Saraschandraa Nov 13 '13 at 05:34
  • Here's a really [simple solution](http://stackoverflow.com/a/21734833/2402866) for adding default text to your spinner. – Alon Levanon Feb 12 '14 at 17:23

11 Answers11

13

Use this code

declaration

String selected, spinner_item;

spinner code

sp.setOnItemSelectedListener(new OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
            selected = sp.getSelectedItem().toString();
            if (!selected.equals("Country"))
                spinner_item = selected;
            System.out.println(selected);

            setid();
        }

        private void setid() {
            sp.setSelection(sp_position);
            t.setText(spinner_item);
        }

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

        }
    });
RajaReddy PolamReddy
  • 22,428
  • 19
  • 115
  • 166
  • If i remove the sp.setSelection(sp_position) the spinner shows the value which is selected – Saraschandraa Nov 13 '13 at 05:18
  • @Saras as per this..My Requirement is whatever is selected in the spinner the Textview should display the selected Item but The spinner should always show the first item or in my case Country..you have to display selected itemm – kalyan pvs Nov 13 '13 at 05:25
  • My problem is once i select the value from the spinner the Textview shows the spinner for few seconds and when the Spinner gets to it default setselection value the Text view shows the default value again. I want the Textview to show the value which is selected from the spinner and not change back to default value of the Spinner – Saraschandraa Nov 13 '13 at 05:26
  • See my edited answer it's working fine. use this code. if you have any doubts let me know. – RajaReddy PolamReddy Nov 13 '13 at 05:42
  • Thanks a lot Mr. Reddy. It works Exactly as i Want. Thanks a lot – Saraschandraa Nov 13 '13 at 05:50
  • can i automatically assign a specific item to my spinner? – Sunny May 19 '20 at 09:00
  • @Sunny Yes, you can spinner.setSelection( item position ). Ex: spinner.setSelection(0). – RajaReddy PolamReddy May 21 '20 at 15:12
10
spinner.setPrompt("Pick One");
demongolem
  • 9,474
  • 36
  • 90
  • 105
raman rayat
  • 404
  • 5
  • 15
5

You only need 3 lines of code for this:

(1) Declare a global variable that is used to save and load the spinner item ID. By global, I mean declaring it right after "public class MainActivity extends Activity {".

int mySpinner_selectedId; 

(2) Then, add the following code AFTER the user has made his/her choice. One good location would be a button that appears together with your spinner.

mySpinner_selectedId = mySpinner.getSelectedItemPosition();

(3) Finally, add the following code right after "mySpinner.setAdapter(adapter);" to load the last selected item.

mySpinner.setSelection(mySpinner_selectedId);

You're most welcomed.

Jun
  • 61
  • 2
  • 3
3

Use android:prompt="@string/select" in spinner....

Abhishek Patel
  • 4,280
  • 1
  • 24
  • 38
2

Do it this way. After setting the textView setSelection to 0th position of your spinner list

sp.setOnItemSelectedListener(new OnItemSelectedListener() {

    @Override
    public void onItemSelected(AdapterView<?> arg0, View arg1,
        int arg2, long arg3) {

        selected = sp.getSelectedItem().toString();
        System.out.println(selected);
        t.setText(selected);
        sp.setSelection(0);
    }
}
frogatto
  • 28,539
  • 11
  • 83
  • 129
Manishika
  • 5,478
  • 2
  • 22
  • 28
  • No after selecting the list it shows the value in Textview for a few seconds and when the Spinner gets to 0th position the Textview gets its value.. – Saraschandraa Nov 13 '13 at 05:19
  • what if i want to automatically set a specif item/value in my spinner?? – Sunny May 19 '20 at 09:05
1

Try this way.

sp.setOnItemSelectedListener(new OnItemSelectedListener() {

    @Override
    public void onItemSelected(AdapterView<?> arg0, View arg1,
            int arg2, long arg3) {
        //selected = sp.getSelectedItem().toString();
        //System.out.println(selected);
        if(arg2!=0)
           t.setText(sp.getSelectedItem().toString());
        sp.setSelection(0);
    }
}

I hope this will help you. Let me know what happens. Thank you.

Gunaseelan
  • 14,415
  • 11
  • 80
  • 128
1

Try this:

    public void onItemSelected(AdapterView<?> parent, View view, 
        int pos, long id) {

           spinner.setSelection(pos);

    }
Richa
  • 700
  • 8
  • 12
0

try this

Countryspinner.setOnItemSelectedListener(new OnItemSelectedListener() {

        public void onItemSelected(AdapterView<?> arg0, View arg1,
                int position, long arg3) {
            if (position == 0) {
                txtSpinner1.setHint("Select Country");
            } else {
                txtSpinner1.setText(CountryList.get(position));
            }

        }

        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
            // TODO Auto-generated method stub
            txtSpinner1.setHint("Select Country");
        }

    });
Invader
  • 679
  • 3
  • 10
  • here i generated the spinner and textview programatically.. you can use set text instead of sethint – Invader Nov 13 '13 at 05:35
0

In onItemSelected method add this code sp.setSelection(0);

frogatto
  • 28,539
  • 11
  • 83
  • 129
jyomin
  • 1,957
  • 2
  • 11
  • 27
  • No Jyoti the Textview displays the value selected for a few seconds. And when the Spinner is made to set to its initial value the Textview is also set to its initial value – Saraschandraa Nov 13 '13 at 05:44
  • paste this inside the method of onItemSelected – jyomin Nov 13 '13 at 05:46
0

I done this in a simple way

  1. Add default text at adapter first or end position(in my case end ) and set this item as default selection. ---- Also get default selection position, So that no action will perform in setOnItemSelectedListener().

    taskName.add("one");
    taskName.add("two");
    taskName.add("select a task");
    ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, taskName);
    binding.spnTask.setAdapter(adapter);
    binding.spnTask.setSelection(adapter.getPosition("select a task name"));
    final int defaultPosition = binding.spnTask.getSelectedItemPosition();
    
  2. Check selected position is default text position

      binding.spnTask.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
    
            if (position == defaultPosition) {
                Toast.makeText(this, "No Action", Toast.LENGTH_SHORT).show();
            }else{  Toast.makeText(this, "Your Action" , Toast.LENGTH_SHORT).show();   }
        }
    
        @Override
        public void onNothingSelected(AdapterView<?> parent) {
    
        }
    });
    
Adarsh Vijayan P
  • 2,964
  • 2
  • 16
  • 27
0
mySpinner = (Spinner) findViewById(R.id.spinner);
        mySpinner.setPrompt("Categorie");
        final ArrayList<String> strDeviceArr = new ArrayList<>();

        mySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String valueSelected = mySpinner.getSelectedItem().toString();
                if(!valueSelected.equals("Categorie"))
                    Toast.makeText(MenuActivity.this, ""+valueSelected, Toast.LENGTH_SHORT).show();

            }

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

            }
        });
BENHISSI Youssef
  • 59
  • 2
  • 2
  • 9