As in a Lerner, assigned to more than one Spinner, know who called him?

Asked

Viewed 57 times

1

I am using 4 spinners in a single Activity and need to receive information from each Spinner. The point is that to use Spinner the "onItemSelected" method is used, and you must assign the value of a variable to "parent.getItemAtPosition(position).toString();".

The point is I’m using 4 spinners within this same method, and I need to assign the "parent.getItemAtPosition(position).toString();" in 4 different variables, however, is assigning the same spinner to the 4 variables.

How do I differentiate the spinners being used in the same method?

2 answers

1

The method onItemSelected receives, in the parameter Parent, the Spinner whose entry was selected.

To know what that is Spinner just check your id .

Anything like that:

public void onItemSelected(AdapterView<?> parent, View view,
        int pos, long id) {
    if(parent.getId() == R.id.spinner1){
        variavel1 = parent.getItemAtPosition(position).toString();
    }
    else if(parent.getId() == R.id.spinner2){
        variavel2 = parent.getItemAtPosition(position).toString();
    }
    ...
    ...
}

Possibly, for the sake of organisation, maintenance and/or better readability, it may be preferable to have a Listener by each of the Spinner.

1


First of all, it’s always best to put the code you once made, or at least a representation, if you can’t put the original code.

Anyway, I will assume that you are implementing the Onselecteditemlistener interface in your Activity and passing this instance to your Spinners:

public class MainActivity implements OnItemSelectedListener {

(...)

spinner.setOnItemClickListener(this);

It turns out that this way, you only have a single Switch for 4 Spinners, when in fact you need 4 listeners.

One way to implement these 4 listeners would be:

spinner1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        // tratar cliques do Spinner 1
    }
});

spinner2.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        // tratar cliques do Spinner 2
    }
});

spinner3.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        // tratar cliques do Spinner 3
    }
});

spinner4.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        // tratar cliques do Spinner 4
    }
});
  • I had done it and it worked, that was the problem. Thanks friend! :)

Browser other questions tagged

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