从Spinner setonItemSelectedListener传递值

时间:2016-07-14 13:40:58

标签: android android-spinner onitemselectedlistener

我正在尝试获取微调器项的位置并将其传递给另一个方法。为了实现这一点,我在MainActivity中声明了一个微调器,并设置了onItemSelectedListener方法(根据用户点击获取位置)。现在我想将onItemselectedListener方法的值传递给另一个方法getItem()。但是getItem()收到的值总是为null。我附上了我的代码以供进一步参考。

public class MainActivity extends AppCompatActivity {
    Spinner spinner;
    String[]array={"I","Me","Myself"};
    String abc;


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

        spinner= (Spinner) findViewById(R.id.spinner);
        spinnerAdapter adapter=new spinnerAdapter(MainActivity.this,android.R.layout.simple_spinner_dropdown_item);
        adapter.addAll(array);
        adapter.add("Select Here");
        spinner.setAdapter(adapter);
        spinner.setSelection(adapter.getCount());

       spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
           @Override
           public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
           abc= String.valueOf(spinner.getSelectedItemPosition()+1);
           }

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

           }
       });

        getitem();
    }

public void getitem()
{
    Log.e("MSG",abc);
}


    }

1 个答案:

答案 0 :(得分:0)

来自Android dev website

响应用户选择

@Override
protected void attachBaseContext(Context base) {
    super.attachBaseContext(base);
    MultiDex.install(this);
}

public class SpinnerActivity extends Activity implements OnItemSelectedListener { ... public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) { // An item was selected. You can retrieve the selected item using // parent.getItemAtPosition(pos) } public void onNothingSelected(AdapterView<?> parent) { // Another interface callback } } ,您可以获取字符串值,并根据需要将其传递给另一个活动。