Question

Now I'm aware that adding listeners, then setting fields would trigger the change. So I set my fields then add listeners.

Ive even added a boolean as it was being triggered, to avoid this. However after OnResume. All my listeners are fireing. Can someone please explain why, and how to stop it. Thanks.

Here is my code/work flow:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

   spn1.setSelection(2);
   spn2.setSelection(15); // Gets replaced by the listener to 2, when it shouldnt!

   UseListeners = false; // Ignores fired events with an IF statement.

   addListeners();

   //UseListeners = true;
}

@Override
protected void onResume() {
    super.onResume();   
    UseListeners = true;
}


private void addListeners() {  
    spn1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
            try{
                if(UseListeners){                       
                    spn2.setSelection(spn1.getSelectedItemPosition());                      
                }
            } catch (Exception e)
            {
            }
        }
        @Override
        public void onNothingSelected(AdapterView<?> arg0) {            
        }
    }); 
 }

Surely after OnResume, nothing is even changing so it shouldnt be firing. On resume literally just sets boolean to true. And it is the last state before the app is running so I'm not sure where and why its then triggering. Its Super is called before being allowed to use triggers too.

Was it helpful?

Solution

I think that listeners are invoked after layout is created. It's looks like creating view happens at some point after onPause() method, so insted of setting your boolean flag in onPause() you should set it in listener.

See here and here.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top