Monday, February 5, 2018

Working with fragments

Leave a Comment

I have the following design:

MainActivity      |                      /->AddingActivity      |-------Fragment One---\->DialogFragment      |-------Fragment Two          |-------Fragment Three      |-------Fragment Four 

MainActivity hold the fragments. Fragment One can start AddingActivity (with context from MainActivity) which adding data to DB and then all fragments should refresh with the new data. DialogFrgment started from FragmentOne is adding some data to SharedPreference and only the FragmentOne should know about this. MainActivity impliments DialogFragment.OnTimeSetListener (The dialog picks time) and then in MainActivity onTimeSet triggers function in Fragment One to refresh the data.

What I did for now is overridden OnCreate in each fragment and the fragment refreshes when it returns back to view. But the app is bit laggy because each fragment refreshes its neighbors and I get some fragment refreshed twice.

Can you please advise me about the correct approach to this design, and how can I make the app work more smooth and correct.

2 Answers

Answers 1

Your approach of MainActivity implementing DialogFragment.OnTimeSetListener and then notifying FragmentOne seems kind of strange.

This is how I would do it:

FragmentOne and MainActivity implement DialogFragment.OnTimeSetListener as well. However, only FragmentOne should be notified from the dialog fragment when the time changes, as it is the one responsible for setting the time. Then when this happens, FragmentOne should notify the activity:

@Override public void onTimeSet(Time time) {     ((DialogFragment.OnTimeSetListener) getActivity().onTimeSet(time); } 

When MainActivity receives the time set event, it must update the other fragments, but if possible, it should not re-create them. Just let them know the time was set so that they can update their views accordingly. Each fragment will update itself depending on what it is displaying, etc.


In case the problem persists and you still have lag, check if you do too much work on the main thread, e.g. a long-running for-loop and try to execute it on another thread.

Answers 2

Maybe you can use LocalBroadcastManager to refresh the the fragments , that way you can have the control to which fragment to refresh and not all at the same time , and you should also check if the DB is causing the lag.

Here is an example how to use LocalBroadcastManager you should implement it on your own way.

https://android--code.blogspot.com/2015/12/android-how-to-send-and-receive-local.html

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment