如何使用微调项目

时间:2011-02-24 19:34:08

标签: java android spinner

我希望在选择特定项目时采取某项行动(例如第2项),但对其他任何项目(例如第1,3,4项)都会采取一般行动。

这是我的代码:

    private String[] array_spinner = new String[4];
    private thetiki mContext;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        setContentView(R.layout.main2);

        array_spinner[0] = "Mathimatika Genikis Paideias";
        array_spinner[1] = "Fusiki Genikis Paideias";
        array_spinner[2] = "Istoria Genikis Paideias";
        array_spinner[3] = "Viologia Genikis Paideias";

        Spinner s = (Spinner)findViewById(R.id.spinner);
        ArrayAdapter adapter = 
            new ArrayAdapter(this, android.R.layout.simple_spinner_item, 
                array_spinner);
        s.setAdapter(adapter);

        // more code
   apostoli.setOnClickListener(new OnClickListener() {

                private AlertDialog show;

                public void onClick(View arg0) {

if (...) {


        if (array_spinner[2] != null) {
            //do something  

        } else if (array_spinner[0] != null || array_spinner[1] != null || array_spinner[3] != null) {

            //do something else
        }
    }

1 个答案:

答案 0 :(得分:4)

在这种情况下,

array_spinner [index]永远不会为null。你已经初始化了它们,它们怎么可能?您需要设置一个侦听器来处理Spinner中的选择,如下所示:

s.setOnItemSelectedListener(new OnItemSelectedListener() {
    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
        if(pos == 2) {
            //do specific action
        } else {
            //do generic action
        }
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {
        //do nothing
    }
});

请参阅Spinner tutorial

中的详细信息