简体   繁体   中英

how to show tne number of selected item of spinner

Where is the issue in code? I want to show in Toast the number of selected item of spinner. When I use num method the app log out me.

    public class MainActivity extends AppCompatActivity {


    String[] dataA = {"Choose type of goal", 
                      "Up to 5", 
                      "Up to 15", 
                      "Up to 23", 
                      "Up to 25"
    };
    int num;

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

    public void setadapter() {
        ArrayAdapter<String> adapterA = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, dataA);
        adapterA.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        Spinner spinnerA = (Spinner) findViewById(spinner);
        spinnerA.setAdapter(adapterA);

    }

    public int getNum() {
        Spinner spinnerA = (Spinner) findViewById(spinner);
        num = spinnerA.getSelectedItemPosition();
        return num;
    }

    public void num(View v) {
        Toast.makeText(getBaseContext(), getNum(), Toast.LENGTH_SHORT).show();
    }
}

You are using the int value of getNum() which is interpreted by the system as a resID ! You should convert your getNum() to a String by using String.valueOf(getNum())

Side Note: You should make your Spinner a global variable and access it in that method instead of recreating the object each time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM