OnItemSelectedListener not working for spinner

吃可爱长大的小学妹 提交于 2019-12-11 13:55:28

问题


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.



来源:https://stackoverflow.com/questions/21845424/onitemselectedlistener-not-working-for-spinner

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!