Get the position of a spinner in Android

前端 未结 4 1339
醉梦人生
醉梦人生 2020-12-14 06:07

I\'m trying to get the position (number) of the spinner when selected to use it in another Activity that will display a different map each time depending on the item selecte

4条回答
  •  青春惊慌失措
    2020-12-14 06:39

    protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            bt = findViewById(R.id.button);
            spinner = findViewById(R.id.sp_item);
            setInfo();
            spinnerAdapter = new SpinnerAdapter(this, arrayList);
            spinner.setAdapter(spinnerAdapter);
    
    
    
            spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView parent, View view, int position, long id) {
                    //first,  we have to retrieve the item position as a string
                    // then, we can change string value into integer
                    String item_position = String.valueOf(position);
    
                    int positonInt = Integer.valueOf(item_position);
    
                    Toast.makeText(MainActivity.this, "value is "+ positonInt, Toast.LENGTH_SHORT).show();
                }
    
                @Override
                public void onNothingSelected(AdapterView parent) {
    
                }
            });
    
    
    
    
    
    
    
    note: the position of items is counted from 0.
    

提交回复
热议问题