Spinner OnItemSelectedListener Issue - android

I have problem with spinner control. I am trying to set spinner items dynamically. Initially I have one item in spinner.
When I try to register the spinner.setOnItemSelect Listener, it immediately call onItemSelected method of it. However I don't want to call this method as soon as my activity get started.
So for this I put a following condition.
public class SpinnerActivity extends Activity implements OnItemSelectedListener {
Spinner spinner;
String[] str_arr = {"aaaaaaaa"};
private int mSpinnerCount=0;
private int mSpinnerInitializedCount=0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_spinner);
spinner = (Spinner) findViewById(R.id.spinner1);
spinner.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, str_arr));
spinner.setOnItemSelectedListener(this);
mSpinnerCount=1;
}
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {
if (mSpinnerInitializedCount < mSpinnerCount) {
mSpinnerInitializedCount++;
}
else {
Intent intent = new Intent(this, NextActivity.class);
startActivity(intent);
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
}
But when I try to select an item on spinner it gives following warning in logcat,
09-03 13:02:02.528: W/InputManagerService(59): Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy#450fafb8
I get the idea that until and unless Item of spinner won't change this method won't be called.
But I have one value in spinner, so how to get the focus, any idea?

Try this to what i said in comment...
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {
if (position > 0) {
//Your actions
}
else {
// Nothing or can show a toast to say user to select a value...
}
}

Try like this
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {
if (position != 0) {
//put your actions here
}
else {
// nothing here or toast
}
}

I think the below code are not right because you implements OnItemSelectedListener
spinner.setOnItemSelectedListener(this);

You get this warning when you try to open already opened window, or try to do something like onFocus on already focused view.
Here you already have the item selected in the Spinner

Related

How to Open a Custom Spinner Item from MainActivity?

I have two activities viz., Activity A and B and I have a spinner in Activity B with 5 options(like country names). On clicking an item, a toast is shown to the user.
//Performing action onItemSelected
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int position,long id) {
Toast.makeText(getApplicationContext(),country[position] ,Toast.LENGTH_LONG).show();
}
In my Activity A, I use a button to open Activity B using Intent. The activity B is opened with the first item of the spinner.
Question
Is there a way so that on clicking the button in Activity A, second spinner item is opened and the respective toast is shown?
you can use the setSelection(int item) method of your spinner (see: https://developer.android.com/reference/android/widget/AbsSpinner.html#setSelection(int)).
For example:
//Activity B
#Override
public void onCreate(Bundle savedInstanceState)
{
//find spinner
spinner.setSelection(1)
}
This answer is based on the assumption that you want to set 2nd item of the array as the default selection.
Use the following code:
final Spinner spinner = (Spinner) view.findViewById(R.id.spinner1);
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(
getActivity(), android.R.layout.simple_spinner_dropdown_item,
getResources().getStringArray(R.array.names));
spinner.setAdapter(arrayAdapter);
spinner.post(new Runnable() {
#Override
public void run() {
spinner.setSelection(1);
}
});
I am late now I think...

Cannot set my Edittext value with change in my spinner selection

I am building an application in which i added a spinner where the user is supposed to select the month and with respect to change in month the edittext field also changes. I made a code by my side but it is not working also not showing any error.
My code is :
public class NewMemberRegister extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
Spinner spinner4;
EditText e1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_member_register);
spinner4=(Spinner)findViewById(R.id.spinner4);
ArrayAdapter adapter3
=ArrayAdapter.createFromResource(this,R.array.period,android.R.layout.simple_spinner_item);
spinner4.setAdapter(adapter3);
spinner4.setOnItemSelectedListener(this);
e1=(EditText)findViewById(R.id.amount);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String str= parent.getItemAtPosition(position).toString();
e1=(EditText)findViewById(R.id.amount);
if (spinner4.getItemAtPosition(position)==0){
e1.setText(" ");
}else if(spinner4.getItemAtPosition(position)==1){
e1.setText("100");
}else if(spinner4.getItemAtPosition(position)==2){
e1.setText("1500");
}else if(spinner4.getItemAtPosition(position)==3){
e1.setText("3500");
}else if(spinner4.getItemAtPosition(position)==4){
e1.setText("6000");
}else if(spinner4.getItemAtPosition(position)==5){
e1.setText("10000");
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
Any Ideas for this?...Comments are Welcome !
Here:
if (spinner4.getItemAtPosition(position)==0){
}else
..
Causing issue. because comparing non Integer type to int value.
As see here:
AdapterView.getItemAtPosition(int) : method takes index of item as int but return Object type value instead of int.
So use Integer.parseInt to get int representing of Object which is returned from getItemAtPosition before comparing it:
if (Integer.parseInt(spinner4.getItemAtPosition(position).toString())==0){
e1.setText(" ");
}else
.....
Do same for other conditions.

Android dependent spinners - onItemSelected does not fire

I tryed to create two dependent spinners. I know there is more than enough of this type of question, but nothing fixed my problem. It seems onItemSelected does not fire at all. I want the second (townships_spinner) change when first spinner (divisions_spinner) is selected or changed. Let's say I have states and cities, when I select the state a want to display only cities from given state. Spinners are created dynamicaly.
That's my code:
public class RegistrationActivity extends Activity implements AdapterView.OnItemSelectedListener {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
createLayout();
}
public void createLayout(){
division_spinner = new Spinner(this);
ArrayAdapter division_adapter = new ArrayAdapter(this,R.layout.spinner,divisions.getList());
divisions_id = viewer.getValueByKey(viewer_form.getViewers_form_viewers_inputname());
division_spinner.setAdapter(division_adapter);
division_spinner.setSelection(divisions.getIndex(divisions_id));
division_spinner.setOnItemSelectedListener(this);
township_spinner = new Spinner(this);
ArrayAdapter township_adapter = new ArrayAdapter(this,R.layout.spinner,townships_map.get(divisions_id));
if (divisions_id == null) {
township_spinner.setEnabled(false);
}
String value = viewer.getValueByKey(viewer_form.getViewers_form_viewers_inputname());
township_spinner.setSelection(townships.getIndex(value, divisions_id));
}
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
Toast.makeText(RegistrationActivity.this, "Yes",Toast.LENGTH_LONG);
if(arg0.equals(division_spinner)) {
Toast.makeText(RegistrationActivity.this, "Yes - You got it!",Toast.LENGTH_LONG);
township_spinner.setEnabled(true);
ArrayAdapter township_adapter = new ArrayAdapter(this, R.layout.spinner, townships_map.get(((Division)division_spinner.getSelectedItem()).getDivisions_id().toString()));
township_spinner.setAdapter(township_adapter);
}
}
public void onNothingSelected(AdapterView<?> arg0) {
}
}
But "Yes" even "Yes - you got it!" toast does not appear.
I guess I miss something stupid, but I cant find it.
you're implementing AdapterView.onItemSelected.
...Just try this instead
Spinner.setOnItemSelectedListener(new OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id)
{
Toast.makeText(topThis, "selected", Toast.LENGTH_LONG).show();
//Call other spinner here to update.
}
#Override
public void onNothingSelected(AdapterView<?> parentView)
{
Toast.makeText(topThis, "nothing selected", Toast.LENGTH_LONG).show();
}
});
Edit: as Prasad says. If you don't have setContentView(View); your activity won't have an xml to inflate, so your views will never get created into anything.
I made a series of mistakes that led to the fact that it did not work as I expected.
First: I forgot to call **show()** on Toast.makeText()
Second: I make a huge mistake when creating ArrayList. I filled ArrayList with data, then I put the list to HashMap and after that I called ArrayList.**clear()**. Which led to override the HashMap values, and that was why it seemed, the spinner was not changing at all...
Well... I feel quite silly ...

Android Spinner : Avoid onItemSelected calls during initialization

I created an Android application with a Spinner and a TextView. I want to display the selected item from the Spinner's drop down list in the TextView. I implemented the Spinner in the onCreate method so when I'm running the program, it shows a value in the TextView (before selecting an item from the drop down list).
I want to show the value in the TextView only after selecting an item from the drop down list. How do I do this?
Here is my code:
import android.app.Activity;
import android.os.Bundle;
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 GPACal01Activity extends Activity implements OnItemSelectedListener {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Spinner spinner = (Spinner) findViewById(R.id.noOfSubjects);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,R.array.noofsubjects_array, 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
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
}
public void onItemSelected(AdapterView<?> parent, View arg1, int pos,long id) {
TextView textView = (TextView) findViewById(R.id.textView1);
String str = (String) parent.getItemAtPosition(pos);
textView.setText(str);
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
spinner.setOnItemSelectedListener(this); // Will call onItemSelected() Listener.
So first time handle this with any Integer value
Example:
Initially Take int check = 0;
public void onItemSelected(AdapterView<?> parent, View arg1, int pos,long id) {
if(++check > 1) {
TextView textView = (TextView) findViewById(R.id.textView1);
String str = (String) parent.getItemAtPosition(pos);
textView.setText(str);
}
}
You can do it with boolean value and also by checking current and previous positions. See here
Just put this line before setting the OnItemSelectedListener
spinner.setSelection(0,false)
This works because setSelection(int, boolean) calls setSelectionInt() internally so that when the listener is added, the item is already selected.
Beware that setSelection(int) won't work, because it calls setNextSelectedPositionInt() internally.
Beginning with API level 3 you can use onUserInteraction() on an Activity with a boolean to determine if the user is interacting with the device.
http://developer.android.com/reference/android/app/Activity.html#onUserInteraction()
#Override
public void onUserInteraction() {
super.onUserInteraction();
userIsInteracting = true;
}
As a field on the Activity I have:
private boolean userIsInteracting;
Finally, my spinner:
mSpinnerView.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View view, int position, long arg3) {
spinnerAdapter.setmPreviousSelectedIndex(position);
if (userIsInteracting) {
updateGUI();
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
As you come and go through the activity the boolean is reset to false. Works like a charm.
This worked for me
Spinner's initialization in Android is problematic sometimes
the above problem was solved by this pattern.
Spinner.setAdapter();
Spinner.setSelected(false); // must
Spinner.setSelection(0,true); //must
Spinner.setonItemSelectedListener(this);
Setting adapter should be first part and onItemSelectedListener(this) will be last when initializing a spinner. By the pattern above my OnItemSelected() is not called during initialization of spinner
haha...I have the same question.
When initViews() just do like this.The sequence is the key, listener is the last. Good Luck !
spinner.setAdapter(adapter);
spinner.setSelection(position);
spinner.setOnItemSelectedListener(listener);
To avoid calling spinner.setOnItemSelectedListener() during initialization
spinner.setSelection(Adapter.NO_SELECTION, true); //Add this line before setting listener
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
My solution:
protected boolean inhibit_spinner = true;
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int pos, long arg3) {
if (inhibit_spinner) {
inhibit_spinner = false;
}else {
if (getDataTask != null) getDataTask.cancel(true);
updateData();
}
}
You can do this by this way:
AdapterView.OnItemSelectedListener listener = new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
//set the text of TextView
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
yourSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
yourSpinner.setOnItemSelectedListener(listener);
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
At first I create a listener and attributed to a variable callback; then i create a second listener anonymous and when this is called at a first time, this change the listener
=]
The user interaction flag can then be set to true in the onTouch method and reset in onItemSelected() once the selection change has been handled. I prefer this solution because the user interaction flag is handled exclusively for the spinner, and not for other views in the activity that may affect the desired behavior.
In code:
Create your listener for the spinner:
public class SpinnerInteractionListener implements AdapterView.OnItemSelectedListener, View.OnTouchListener {
boolean userSelect = false;
#Override
public boolean onTouch(View v, MotionEvent event) {
userSelect = true;
return false;
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
if (userSelect) {
userSelect = false;
// Your selection handling code here
}
}
}
Add the listener to the spinner as both an OnItemSelectedListener and an OnTouchListener:
SpinnerInteractionListener listener = new SpinnerInteractionListener();
mSpinnerView.setOnTouchListener(listener);
mSpinnerView.setOnItemSelectedListener(listener);
create a boolean field
private boolean inispinner;
inside oncreate of the activity
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (!inispinner) {
inispinner = true;
return;
}
//do your work here
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
Similar simple solution that enables multiple spinners is to put the AdapterView in a collection - in the Activities superclass - on first execution of onItemSelected(...) Then check to see if the AdapterView is in the collection before executing it. This enables one set of methods in the superclass and supports multiple AdapterViews and therefor multiple spinners.
Superclass ...
private Collection<AdapterView> AdapterViewCollection = new ArrayList<AdapterView>();
protected boolean firstTimeThrough(AdapterView parent) {
boolean firstTimeThrough = ! AdapterViewCollection.contains(parent);
if (firstTimeThrough) {
AdapterViewCollection.add(parent);
}
return firstTimeThrough;
}
Subclass ...
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
if (! firstTimeThrough(parent)) {
String value = safeString(parent.getItemAtPosition(pos).toString());
String extraMessage = EXTRA_MESSAGE;
Intent sharedPreferencesDisplayIntent = new Intent(SharedPreferencesSelectionActivity.this,SharedPreferencesDisplayActivity.class);
sharedPreferencesDisplayIntent.putExtra(extraMessage,value);
startActivity(sharedPreferencesDisplayIntent);
}
// don't execute the above code if its the first time through
// do to onItemSelected being called during view initialization.
}
Try this
spinner.postDelayed(new Runnable() {
#Override
public void run() {
addListeners();
}
}, 1000);.o
Code
spinner.setOnTouchListener(new View.OnTouchListener() {
#Override public boolean onTouch(View view, MotionEvent motionEvent) { isSpinnerTouch=true; return false; }});
holder.spinner_from.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int slot_position, long l) {
if(isSpinnerTouch)
{
Log.d("spinner_from", "spinner_from");
spinnerItemClickListener.onSpinnerItemClickListener(position, slot_position, AppConstant.FROM_SLOT_ONCLICK_CODE);
}
else {
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
You could achieve it by setOnTouchListener first then setOnItemSelectedListener in onTouch
#Override
public boolean onTouch(final View view, final MotionEvent event) {
view.setOnItemSelectedListener(this)
return false;
}
This worked for me:
spinner.setSelection(0, false);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
spinner.setOnItemSelectedListener(listener);
}, 500);
Based on Abhi's answer i made this simple listener
class SpinnerListener constructor(private val onItemSelected: (position: Int) -> Unit) : AdapterView.OnItemSelectedListener {
private var selectionCount = 0
override fun onNothingSelected(parent: AdapterView<*>?) {
//no op
}
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
if (selectionCount++ > 1) {
onItemSelected(position)
}
}
}
You can create custom OnItemSelectedListener like this. I've taken val check=0 and in onItemSelected() method i did check if its count is 0? If 0 means its called during initialization. So simply ignore it.
I've also called separate abstract method called onUserItemSelected() I'll call this method is check > 0. This works perfectly fine for me.
abstract class MySpinnerItemSelectionListener : AdapterView.OnItemSelectedListener {
abstract fun onUserItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long)
private var check = 0
override fun onItemSelected(
parent: AdapterView<*>?,
view: View,
position: Int,
id: Long
) {
if (++check > 1) {
onUserItemSelected(parent, view, position, id)
}
}
override fun onNothingSelected(parent: AdapterView<*>?) {}
}
And then you can set listener like this.
mySpinner.onItemSelectedListener = object : MySpinnerItemSelectionListener() {
override fun onUserItemSelected(
parent: AdapterView<*>?,
view: View?,
position: Int,
id: Long
) {
//your user selection spinner code goes here
}
}
Had the same problem and this works for me:
I have 2 spinners and I update them during init and during interactions with other controls or after getting data from the server.
Here is my template:
public class MyClass extends <Activity/Fragment/Whatever> implements Spinner.OnItemSelectedListener {
private void removeSpinnersListeners() {
spn1.setOnItemSelectedListener(null);
spn2.setOnItemSelectedListener(null);
}
private void setSpinnersListeners() {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
spn1.setOnItemSelectedListener(MyClass.this);
spn2.setOnItemSelectedListener(MyClass.this);
}
}, 1);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// Your code here
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
When the class is initiating use setSpinnersListeners() instead of directly setting the listener.
The Runnable will prevent the spinner from firing onItemSelected right after the you set their values.
If you need to update the spinner (after a server call etc.) use removeSpinnersListeners() right before your update lines, and setSpinnersListeners() right after the update lines. This will prevent onItemSelected from firing after the update.
For me, Abhi's solution works great up to Api level 27.
But it seems that from Api level 28 and upwards, onItemSelected() is not called when listener is set, which means onItemSelected() is never called.
Therefore, I added a short if-statement to check Api level:
public void onItemSelected(AdapterView<?> parent, View arg1, int pos,long id) {
if(Build.VERSION.SDK_INT >= 28){ //onItemSelected() doesn't seem to be called when listener is set on Api 28+
check = 1;
}
if(++check > 1) {
//Do your action here
}
}
I think that's quite weird and I'm not sure wether others also have this problem, but in my case it worked well.
I placed a TextView on top of the Spinner, same size and background as the Spinner, so that I would have more control over what it looked like before the user clicks on it. With the TextView there, I could also use the TextView to flag when the user has started interacting.
My Kotlin code looks something like this:
private var mySpinnerHasBeenTapped = false
private fun initializeMySpinner() {
my_hint_text_view.setOnClickListener {
mySpinnerHasBeenTapped = true //turn flag to true
my_spinner.performClick() //call spinner click
}
//Basic spinner setup stuff
val myList = listOf("Leonardo", "Michelangelo", "Rafael", "Donatello")
val dataAdapter: ArrayAdapter<String> = ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, myList)
my_spinner.adapter = dataAdapter
my_spinner.onItemSelectedListener = object : OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>?, view: View, position: Int, id: Long) {
if (mySpinnerHasBeenTapped) { //code below will only run after the user has clicked
my_hint_text_view.visibility = View.GONE //once an item has been selected, hide the textView
//Perform action here
}
}
override fun onNothingSelected(parent: AdapterView<*>?) {
//Do nothing
}
}
}
Layout file looks something like this, with the important part being that the Spinner and TextView share the same width, height, and margins:
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Spinner
android:id="#+id/my_spinner"
android:layout_width="match_parent"
android:layout_height="35dp"
android:layout_marginStart="10dp"
android:layout_marginEnd="10dp"
android:background="#drawable/bg_for_spinners"
android:paddingStart="8dp"
android:paddingEnd="30dp"
android:singleLine="true" />
<TextView
android:id="#+id/my_hint_text_view"
android:layout_width="match_parent"
android:layout_height="35dp"
android:layout_marginStart="10dp"
android:layout_marginEnd="10dp"
android:background="#drawable/bg_for_spinners"
android:paddingStart="8dp"
android:paddingEnd="30dp"
android:singleLine="true"
android:gravity="center_vertical"
android:text="*Select A Turtle"
android:textColor="#color/green_ooze"
android:textSize="16sp" />
</FrameLayout>
I'm sure the other solutions work where you ignore the first onItemSelected call, but I really don't like the idea of assuming it will always be called.
I solved this problem like this:
In the activity lifecycle method whose name is onResume():
I added Spinner.setOnItemSelectedListener(this);
As a result, when our spinner call onclick method in the initialize, it does not work.
onResume method starts working when the finished Android page is displayed.

Android Spinner - onItemSelected / setOnItemSelectedListener not triggering

This is driving me nuts since it's something I've done before but can't figure out why it isn't working now...
I've got a menu button, implemented in the usual way via a menu.xml file and the onOptionsItemSelected method with a switch in it, that creates and displays a spinner.
I've added the setOnItemSelectedListener, but it never seems to trigger. The spinner appears, I pick an option or back out, neither onItemSelected or onNothingSelected are called.
Here is all the code between the "case" and "return true" of the menu-button-handling switch statement. (topThis is a variable referring to the context of the activity - works fine for all other toasts in the app)
String[] widgetModes = {"Mode 1", "Mode2"};
ArrayAdapter<String> widgetModeAdapter = new ArrayAdapter<String> (this, android.R.layout.simple_spinner_item, widgetModes);
widgetModeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner widgetModeSpinner = new Spinner(this);
widgetModeSpinner.setAdapter(widgetModeAdapter);
widgetModeSpinner.setPrompt("Choose Widget Mode");
widgetModeSpinner.setOnItemSelectedListener(new OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id)
{
Toast.makeText(topThis, "derp", Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> parentView)
{
Toast.makeText(topThis, "herf", Toast.LENGTH_LONG).show();
}
});
widgetModeSpinner.performClick();
Any ideas? I vaguely suspect that the fact I'm creating the Spinner programmatically is the problem...
I had the similar problem when I was implementing a spinner, I resolved it by getting the parent View and set Adapter-
spinner1 =(Spinner)findViewById(R.id.spinner1);
spinner1.setAdapter(BindSpinner("ProgramMaster",cols,null,true,""));
spinner1.setOnItemSelectedListener(new OnItemSelectedListener()
{
protected Adapter initializedAdapter=null;
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id)
{
if(initializedAdapter !=parentView.getAdapter() ) {
initializedAdapter = parentView.getAdapter();
return;
}
String selected = parentView.getItemAtPosition(position).toString();
if(abc.equals("Select") && !selected.equals("Select"))
{
do something
}
else
{
Do something
}
textQualification=selected;
SearchUpdated("Qualification");
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}
});
Remember that you can't re-select the same spinner item, it always sets the first item as selected if you are not adding some custom code to handle the spinner selection.
For the Toast not showing, I would suggest to always use the "MyActivity.this" as your context when creating a Toast inside a listener interface like this:
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
/**
* Called when a new item is selected (in the Spinner)
*/
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
// An spinnerItem was selected. You can retrieve the selected item using
// parent.getItemAtPosition(pos)
Toast.makeText(MyActivity.this, "Hello Toast",Toast.LENGTH_SHORT).show();
}
public void onNothingSelected(AdapterView<?> parent) {
// Do nothing, just another required interface callback
}
}); // (optional)
And the .show() at the end is easy to forget sometimes;)
Actually, if your spinner visibility is set to gone then it will trigger the click of it when you call performclick() method but it will not trigger its setOnItemSelectedListener
so you need to change the visibility then it will work
I know the question is a bit old, but in case you are waiting for a AsyncTask callback, make sure that you let your adapter know of the data changes by calling notifyDataSetChanged() on the callback thread!
#Override
public void onPostExecute(String result) {
///do something with your data
spinnerArrayAdapter.notifyDataSetChanged();
}

Categories

Resources