OnItemSelectedListener not working for spinner

2019-08-11 08:09发布

问题:

I have a spinner which I have set up using a custom ArrayAdapter:

    private static class CustomAdapter<T> extends ArrayAdapter<String> {
    public CustomAdapter(Context context, int textViewResourceId, String[] objects) {
        super(context, textViewResourceId, objects);
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        View view = super.getView(position, convertView, parent);
        TextView textView = (TextView) view.findViewById(android.R.id.text1);
        textView.setText("");
        return view;
    }       

It is initialized as follows (the Spinner spinner; statement is up above as a class variable):

    this.spinner = (Spinner) findViewById(R.id.spinner1);
    CustomAdapter<String> adapter = new CustomAdapter<String>(this, 
        android.R.layout.simple_spinner_dropdown_item, new String[] {"Set Homepage"});

    spinner.setAdapter(adapter);
    spinner.setOnItemSelectedListener(this);

I have implemented the OnItemSelectedListener:

public class MainActivity extends Activity implements OnItemSelectedListener{...}

And have the required callbacks:

    //spinner methods
@Override
public void onItemSelected(AdapterView<?> parent, View view, 
        int pos, long id) {
    // TODO Auto-generated method stub
    //if (pos == 1){
        Toast.makeText(this, "Person wants to change the homepage", Toast.LENGTH_SHORT).show();
    //}
}

@Override
public void onNothingSelected(AdapterView<?> parent) {
    // TODO Auto-generated method stub
    //Toast.makeText(this, "Person wants to change the homepage", Toast.LENGTH_SHORT).show();

}

The xml for the spinner:

            <Spinner
            android:id="@+id/spinner1"
            android:layout_width="45dp"
            android:layout_height="45dp"
            android:background="@drawable/ic_menu_moreoverflow_holo_dark" />

The problem is, whenever an item is selected from the spinner, nothing at all happens, even after I removed all conditions as you can see above.

回答1:

OnItemSelectedListener not working for spinner

Because you are passing only one item in Adapter which is by default selected. Probably you are getting toast message when starting your Application.

So add more elements to check OnItemSelectedListener behavior.