List values of an array in a spinner, and when an item is selected print its value from another array

4

I have a spinner that lists the types of person (physical and legal - Respectively IDs = 1 and 2) and would like to select one of them, to be printed on a Toast ID .

//array tipoPessoa
private String[] tipoPessoa = new String[]{"física", "jurídica"};

//array idPessoa
private String[] tipoPessoaId = new String[]{"1", "2"};

The following code snippet is how I can print the id of the item, however I want to print its value in the array tipoPessoaId as its position in tipoPessoa :

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, tipoPessoa);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        sp = (Spinner) findViewById(R.id.sp_tipo_pessoa);
        sp.setAdapter(adapter);

        sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String idTipoPessoa = "O ID é: " + parent.getItemIdAtPosition((int) id);
                Toast.makeText(parent.getContext(), idTipoPessoa, Toast.LENGTH_LONG).show();
            }

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

            }
        });
    
asked by anonymous 31.10.2017 / 21:35

1 answer

2

The position parameter gives you the position of View in Adapter and subsequently the position of the chosen element in the array passed to Adapter .

You just need to access the same position in the other array:

@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
    String idTipoPessoa = "O ID é: " + tipoPessoaId[position];//<---aqui
    Toast.makeText(parent.getContext(), idTipoPessoa, Toast.LENGTH_LONG).show();
}
    
01.11.2017 / 20:27