android - How to add OnItemSelectedListener for one Spinner in multiple Fragments -


in actionbaractivity use viewpager different fragments. use spinner in supportactionbar populate fragments in viewpager.

if write code in 1 fragment application works intended. if add same method in second fragment well, onitemselectedlistener first fragment not called more.

@override public void onactivitycreated(@nullable bundle savedinstancestate) {     super.onactivitycreated(savedinstancestate);     spinner spinner = (spinner) ((actionbaractivity) getactivity()).getsupportactionbar().getcustomview().findviewbyid(r.id.actionbar_spinner_names);     spinner.setonitemselectedlistener(new adapterview.onitemselectedlistener() {         @override         public void onitemselected(adapterview<?> parent, view view, int position, long id) {             oncontentchanged(position);         } 

is possible share setonitemselectedlistener of menuitem amonst different fragments? or there better way share selection of actionbarspinner amongst fragments of application?

edit: have tablayout 2 fragments. spinner used query filter results in both fragments. want update both fragments user makes selection. can't register in onitemselectedlistener both fragments. hope makes little clearer. sadly can't upload pictures yet.

you can set 1 listener spinner. can achieve need if activity hosts fragments has access them.

you create nested class in activity hosts viewpager , fragments. attach listener spinner custom constructor takes fragments parameters

class mylistener implements adapterview.onitemselectedlistener {      fragment frag1;      fragment frag2;       public mylistener(fragment f1, fragment f2)       {         frag1 = f1;         frag2 = f2;      }       @override         public void onitemselected(adapterview<?> parent, view view, int position, long id) {             if (f1 != null)             {             }             ....         }     } 

then in activity create listener with

spinner spinner = (spinner) ((actionbaractivity) getactivity()).getsupportactionbar().getcustomview().findviewbyid(r.id.actionbar_spinner_names); spinner.setonitemselectedlistener(new mylistener(fragment1, fragment2)); 

how work , how easy create listener depend on implementation of tablayout.


Comments

Popular posts from this blog

python - Healpy: From Data to Healpix map -

c - Bitwise operation with (signed) enum value -

xslt - Unnest parent nodes by child node -