微调的setOnItemSelectedListener不叫(setOnItemSelectedLi

2019-09-03 14:31发布

我用setOnItemSelectedListener指定哪个项目的微调选择,但我认为它不叫。 它应打印“它的工作原理”的程序运行时。

XML代码:

<Spinner
    android:id="@+id/quantity"
    android:layout_width="94dp"
    android:layout_height="27dp"
    android:layout_x="11dp"
    android:layout_y="118dp"
     />

Java代码:

public class quantity extends Activity
{

Spinner  quantity;


    public void onCreate(Bundle savedInstanceState) 
    {
    quantity=(Spinner)findViewById(R.id.quantity);

    quantity.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() 
            {
                public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) 
                {
                    Object item = parent.getItemAtPosition(pos);

                    System.out.println("it works...   ");

                }

                public void onNothingSelected(AdapterView<?> parent) 
                {

                }
            });


    }

}

Answer 1:

试试这个

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

            /*for fill your Spinner*/
        List<String> spinnerArray = new ArrayList<String>();
        spinnerArray.add("Item 1");
        spinnerArray.add("Item 2");
        spinnerArray.add("Item 3");
        spinnerArray.add("Item 4");
        spinnerArray.add("Item 5");

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_spinner_item, spinnerArray);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        Spinner spinner = (Spinner) findViewById(R.id.quantity);
        spinner.setAdapter(adapter);

        spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view,
                    int position, long id) {
                Object item = adapterView.getItemAtPosition(position);
                if (item != null) {
                    Toast.makeText(MainActivity.this, item.toString(),
                            Toast.LENGTH_SHORT).show();
                }
                Toast.makeText(MainActivity.this, "Selected",
                        Toast.LENGTH_SHORT).show();

            }

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

            }
        });
    }


Answer 2:

你已经错过的setContentView(R.layout.yourlayout);



文章来源: setOnItemSelectedListener of Spinner does not call