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

Asked

Viewed 214 times

4

I have a spinner that lists the types of person (physical and legal - respectively Ids = 1 and 2) and would like when selecting one of them, to be printed in a Toast your 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 on array tipoPessoaId in accordance with his 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) {

            }
        });
  • Wants you to go fisica prints 1 because it is the element in the same position 0 of the other array, and jurídica prints 2 for the same reason ?

  • That’s right Isac

2 answers

2


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

So you just need to access at 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();
}

0

There is another topic that also shows a way to do this, but in another context, that of nested spinners:

Spinner together

Browser other questions tagged

You are not signed in. Login or sign up in order to post.