android - How to add OnItemSelectedListener for one Spinner in multiple Fragments -
in actionbaractivity
use viewpager
different fragment
s. 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 fragment
s? or there better way share selection of actionbarspinner
amongst fragment
s of application?
edit: have tablayout
2 fragment
s. spinner
used query filter results in both fragment
s. want update both fragments
user makes selection. can't register in onitemselectedlistener
both fragment
s. 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
, fragment
s. attach listener spinner
custom constructor takes fragment
s 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
Post a Comment