android - Communication between SlidingTabLayout tabs -
i've searched lot on how communicate between fragments using slidingtablayout haven't got answer. know using actionbar wanted new way android lollipop using slidingtablayout. tried this-> http://android-er.blogspot.in/2012/06/communication-between-fragments-in.html wanted material design. referred link http://www.android4devs.com/2015/01/how-to-make-material-design-sliding-tabs.html making material design sliding tabs. now wanted know how communicate between sliding tabs. i've tried lot couldn't find answer looking for. appreciated.
the cleanest way define interface activity
contains fragment
s implement. how solved this:
first define interface in it's own file, because has visible other classes.
public interface fragmentcommunication { public void printmessage(string message); .... }
in activity
need implement interface
public class mainactivity extends actionbaractivity implements fragmentcommunication { .... public void printmessage(string message) { system.out.println(message); } }
finally in fragment
s can hosting activity
getactivity()
, use communication methods cast activity implemented communication interface so:
((fragmentcommunication) getactivity()).printmessage("hello fragment!");
edit: further pass message other fragment
s this: since tabs extend fragment
best create interface
public interface receiverinterface { public void receivemessage(string str); }
then implement in tabs
public class tab1 extends fragment implements receiverinterface { .... code ..... public void receivestring(string str) { //use str } }
to further send message other fragments required activity sees them. example modify printmessage()
activity
implements
public void printmessage(string message) { system.out.println(message); //send message came 1 fragment if (tabfragment1 instanceof receiverinterface){ ((receiverinterface) tabfragment1).receivemessage(message); } }
Comments
Post a Comment