FragmentTabHost性能缓慢?

9
我使用了v4 support lib来实现FragmentTabHost。要求是切换标签时,每次都会调用onCreateView()onActivityCreated()方法。这导致我的代码性能很慢。有没有其他解决方案?如何提高片段选项卡的性能?

дҪ иғҪеҗҰеҸ‘еёғдҪ зҡ„onCreateView()е’ҢonActivityCreated()зҡ„д»Јз Ғпјҹ - Darwind
你尝试过在你的Fragment中使用setRetainInstance(true)吗? - Artem Zelinskiy
4个回答

9

听起来像是一种设计上的问题。

重新设计你的代码,使得繁重的工作可以异步地完成。片段应该能够快速构建。如果有任何需要处理的大量数据以便Fragment显示有用的信息,那么这些处理工作应该在Fragment创建之前或异步完成,并且当工作完成时,Fragment应该被通知更新其内容。


3
同意。如果 onCreateView()onActivityCreated() 两者总共花费的时间超过几毫秒,那么就做错了。 - CommonsWare

1

首先要注意的是计算/加载大量数据应该放在与主UI线程不同的工作线程上。我认为最好的选择是使用AsyncTask。您可以在Fragment中使用类似以下内容的代码:

private class LoadData extends AsyncTask<Void, Void, Void>{

      @Override
      protected void onPreExecute(){
          super.onPreExecute();
          // this is the place where you can show
          // progressbar for example to indicate the user
          // that there is something which is happening/loading in the background
      }

      @Override
      protected void doInBackground(Void... params){

          // that's the place where you should do 
          // 'the heavy' process which should run on background thread
      }

      @Override
      protected void onPostExecute(Void result){
          super.onPostExecute();
          // you should update your UI here.
          // For example set your listview's adapter
          // changes button states, set text to textview and etc.
      }
}

这是使选项卡更快的方法。希望这能帮到你!: )

1
我找到了一个解决方法。我将所有的网络服务和数据库事务代码都插入到oncreate中,因为oncreate只有在ondestroy没有被调用时才会被调用。另外还有另一种解决方法可以使用。

fragment.show();

& fragment.hide(); 方法


1
听起来你有正确的想法。然而,最终目标是Fragment不应该与它们的Activity交流以检索数据。它们应该被赋予所有必要的资源引用,以便自己获取数据。毕竟这就是Fragment的意义所在。Activity只是负责初始化和导航的容器。 - dcow
@saunik Sing:请问我在哪里需要使用fragment.show()和fragment.hide()函数?我需要重写onTabChanged函数吗? - Alok Rao

0
作为 Android 开发者的补充:如果您已经在使用 AsyncTask,请记住,即使您使用多个 AsyncTask,它们也是按顺序依次执行的!如果您想要更多的线程来处理任务,请查看这篇文章,它完美地解释了如何实现!同时运行多个 AsyncTasks -- 不可能吗?

1
这取决于您正在运行的版本和设备硬件。异步任务在线程池中执行,其中简单情况是1个工作线程的线程池。这也是某些框架版本的默认值。 - dcow

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接