Android: problems with getSelectedItem on a spinner

后端 未结 6 1578
旧时难觅i
旧时难觅i 2021-01-27 00:35

I have a Spinner, and put the selected item in the body of a mail. this is my code:

@Override
protected void onCreate(Bundle savedInstanceState) {
         


        
6条回答
  •  北荒
    北荒 (楼主)
    2021-01-27 00:39

    Your are getting the selected item before the actual rendering of the spinner. It depends on device to device that how fast it renders the screen. Rather then getting the selected item in getSelectionItem() in the onCreate() method try out to do it in the onClickListener() of your Button.

        @Override 
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_modulo);
    
            Spinner spinnerTaglia = (Spinner) findViewById(R.id.spinnerTaglia);
    
        // Create an ArrayAdapter using the string array and a default spinner layout ArrayAdapter adapter = ArrayAdapter.createFromResource(this,     R.array.Taglie, android.R.layout.simple_spinner_item); 
    
        // Specify the layout to use when the list of choices appears adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); 
            spinnerTaglia.setPrompt("Seleziona la taglia!");
    
        // Apply the adapter to the spinner 
            spinnerTaglia.setAdapter(new NothingSelectedSpinnerAdapter(
                    adapter, 
                    R.layout.contact_spinner_row_nothing_selected,
                    // R.layout.contact_spinner_nothing_selected_dropdown, // Optional 
                    this));
    
    
    
    
            Button btnCompilaOrdine = (Button) findViewById(R.id.btnCompilaOrdine);
            btnCompilaOrdine.setOnClickListener(new View.OnClickListener(){
    
                public void onClick(View arg0) {
    
            //Get the Selected item from the spinner
            final String taglia = spinnerTaglia.getSelectedItem().toString();
            Intent i = new Intent(Intent.ACTION_SEND);
            i.setType("message/rfc822");
            i.putExtra(Intent.EXTRA_EMAIL  , new String[]{"MAIL@gmail.com"});
            i.putExtra(Intent.EXTRA_SUBJECT, "MAIL OBJECT");
            i.putExtra(Intent.EXTRA_TEXT   , "Taglia: "+taglia);
            try { 
                startActivity(Intent.createChooser(i, "Send mail..."));
            } catch (android.content.ActivityNotFoundException ex) {
                Toast.makeText(Modulo.this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
            } 
    
            } 
            }); 
        } 
    

提交回复
热议问题