Search code examples
androidandroid-event

Best way to handle multiple event listeners


Let's say I have a spinner(with 2 items) and a radiogroup (with 2 radiobuttons).

I want to show for example a TextView in my layout which will be with different values for every choice:

For example we have:

Spinner

Male
Female

RadioGroup

True False

So we have 4 cases:

  1. Male True
  2. Female False
  3. Male False
  4. Female True

In short, each time user selects any of these choices, I want to show a different textview. I have placed event listeners on spinners and radiobuttons:

Spinner Listener

spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View arg1,
                int arg2, long arg3) {
            ``// TODO Auto-generated method stub
        }

Radio Group Listener

radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                // TODO Auto-generated method stub
                          //switch checkedId and check which spinner item is selected...
                          //then show the textview
                     }

But this sometimes works sometimes not- I am having many and different problems. I also tried similar choices. But nothing worked preperly.

How can dynamically handle this without adding an extra button?


Solution

  • Hopefully this better explains my comment.

    int selectedSpinnerItem = -1;
    int selectedRadioGroupItem = -1;
    
    spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
            selectedSpinnerItem = position;
            updateViews();
        }
    
        @Override
        public void onNothingSelected(AdapterView<?> parent) {
            selectedSpinnerItem = -1;
            updateViews();
        }
    });
    
    radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            selectedRadioGroupItem = checkedId;
            updateViews();
        }
    });
    
    public void updateViews(){
        // Here is where you will compare the values 
        // and display the appropriate views.
    }