android - What is the proper way to send data from one fragment to another? -
android - What is the proper way to send data from one fragment to another? -
i have fragment
"pick year" button. button adds listfragment
backstack, user can pick year. 1 time year chosen, want dispose of listfragment
, homecoming first fragment. best way update first fragment, info selected in listfragment
?
tl;dr: fragment1 opens fragment2, user chooses alternative in fragment2. how update fragment1 data?
my current solution public class static members, i'm wondering if android
has improve way.
all fragment-to-fragment communication done through associated activity. 2 fragments should never communicate directly. [source]
define interface in fragment2, , implement interface in host activity. when phone call interface method fragment2, can access fragment1 within interface method on activity , pass appropriate info fragment1 via public methods.
create interface:
public class fragment2 extends listfragment { onitemselectedlistener mcallback; public interface onitemselectedlistener { public void onitemselected(int position); } @override public void onattach(activity activity) { super.onattach(activity); seek { mcallback = (onitemselectedlistener ) activity; } grab (classcastexception e) { throw new classcastexception(activity.tostring() + " must implement onitemselectedlistener"); } } @override public void onlistitemclick(listview l, view v, int position, long id) { mcallback.onitemselected(position); } }
add implements fragment2.onitemselectedlistener
activity definition, , define onitemselected method:
public void onitemselected(int position) { fragment1 fragment = (fragment1) getsupportfragmentmanager().findfragmentbyid(r.id.fragment1); if (fragment != null) { fragment.updatevalue(position); } }
android android-activity android-fragments
Comments
Post a Comment