Changing Tabs is Slow/Laggy - Using Fragments

妖精的绣舞 提交于 2019-11-29 20:57:53

问题


I have an Activity that uses tabs, and the tabs switch Fragments. The problem is that the Fragment take a few seconds to load when being created, thus switching tabs has a delay of about 1 or 2 seconds. To fix this I have been trying to find a way to display a simple Loading graphic or even a progress dialog, so that the tab changes instantly and displays something indicating things are loading until everything completes.

My onCreateView method of the Fragment looks like this:

FrameLayout fl;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    fl = (FrameLayout) inflater.inflate(R.layout.text_layout, container, false);

    doHeavyStuff();

    return fl;
 }

I tried putting doHeavyStuff() in onStart() but that did not help anything. And a Thread won't help because doHeavyStuff() involves manipulating views/GUI.

Any ideas on how I can display the Fragment and display "Loading" information while everything else loads?

Thanks!

Matt.


回答1:


In the onActivityCreated() :

  • Start a progress bar(or any progress showing UI element/s).
  • Execute the HeavyStuffDoingAsyncTask which is explained below.

HeavyStuffDoingAsyncTask should have:

  • doHeayStuff()'s logic which doesn't update ui in the doInBackground method.
  • call publishProgress() from doInBackground() everytime you want to update the ui.
  • Implement the UI updating logic in the onProgressUpdate method.
  • Stop the progress bar in the onPostExecute method.

Good Luck.




回答2:


try to set

pager.setOffscreenPageLimit(no_of_fragments or pages);


来源:https://stackoverflow.com/questions/9237431/changing-tabs-is-slow-laggy-using-fragments

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!