单击时,微调器会转动项目名称,而不是项目的数值

时间:2016-11-09 05:56:23

标签: android android-spinner

我制作了一个Spinner,每次点击该项目时都会给项目名称  但相反,我想干杯项目的数值 这是我的main.java文件。

    Spinner spinner1, spinner2;
    private Button btnSubmit;

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

        addListenerOnSpinnerItemSelection();
    }

    // add items into spinner dynamically
    public void addListenerOnSpinnerItemSelection() {
        spinner1 = (Spinner) findViewById(R.id.spinner1);
        spinner1.setOnItemSelectedListener(new CustomOnItemSelectedListener());
    }
}

这是我的CustomOnItemSelectedListener.java文件。

    package com.dev.app.dropdown;

    import android.view.View;
    import android.widget.AdapterView;
    import android.widget.Toast;


    public class CustomOnItemSelectedListener implements     AdapterView.OnItemSelectedListener {
    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
        Toast.makeText(parent.getContext(),
                "OnItemSelectedListener:" +     parent.getItemAtPosition(pos).toString(),
                Toast.LENGTH_SHORT).show();
    }

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

2 个答案:

答案 0 :(得分:0)

请尝试以下代码。

spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Spinner MySpinner = (Spinner) findViewById(R.id.spinner);
                Integer indexValue = MySpinner.getSelectedItemPosition();
                Toast.makeText(EditPlanActivity.this, "value" + indexValue + " pos " + position, Toast.LENGTH_LONG).show();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

答案 1 :(得分:0)

而不是使用

parent.getItemAtPosition(pos).toString()

使用

Spinner.getSelectedItem().toString();

完整代码:

@Override
    public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {

  String selectItem = Spinner.getSelectedItem().toString();
  Toast.makeText(parent.getContext(),
                "OnItemSelectedListener:" +  selectItem,
                Toast.LENGTH_SHORT).show();
    }

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