Sending Data To The Container Activity
I have this issue of sending some data back and forth between a fragment and its container activity, I succeeded in doing it. What puzzles me is sending my data from the fragment t
Solution 1:
The Right approach is to use Interfaces. Don't use onStop or setRetainInstance()
See this. It will solve you problem. Pass data from fragment to actvity
Solution 2:
You can also achieve this by using Interface
, using an EventBus
like LocalBroadcastManager
, or starting a new Activity
with an Intent
and some form of flag
passed into its extras
Bundle or something else.
Here is an example about using Interface:
1. Add function sendDataToActivity()
into the interface (EventListener
).
//EventListener.javapublicinterfaceEventListener {
publicvoidsendDataToActivity(String data);
}
2. Implement this functions in your MainActivity
.
// MainActivity.javapublicclassMainActivityextendsAppCompatActivityimplementsEventListener {
@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@OverridepublicvoidsendDataToActivity(String data) {
Log.i("MainActivity", "sendDataToActivity: " + data);
}
}
3. Create the listener in MyFragment
and attach
it to the Activity
.
4. Finally, call function using listener.sendDataToActivity("Hello World!")
.
// MyFragment.java publicclassMyFragmentextendsFragment {
privateEventListener listener;
@OverridepublicvoidonAttach(Activity activity)
{
super.onAttach(activity);
if(activity instanceofEventListener) {
listener = (EventListener)activity;
} else {
// Throw an error!
}
}
@OverridepublicViewonCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_my, container, false);
// Send data
listener.sendDataToActivity("Hello World!");
return view;
}
@OverridepublicvoidonDetach() {
super.onDetach();
listener = null;
}
}
Hope this will help~
Post a Comment for "Sending Data To The Container Activity"