2014-08-30 99 views
1

我有一个活动,其中包含一个导航抽屉,当按下不同的导航项时会显示不同的片段。问题是这些碎片中的一个在加载时有明显的延迟。Android - 在交换片段之前加载片段的视图

在我的活动的onCreate方法中,我启动了一个线程,我要预先加载每个片段,以便在用户按下导航项时可以很容易地进行交换。

我的代码看起来是这样的:

public class MainActivity extends Activity { 
    protected void OnCreate { 
     // Get instance of Thread InitialiseNavFrags. 
     InitialiseNavFrags fragmentInit = new InitialiseNavFrags(); 
     fragmentInit.start(); 
    } 
    private void selectItem(position) { 
     ... 
     final FragmentTransaction ft = getFragmentManager().beginTransaction(); 
     // Wait until sportsFragment is loaded. 
     while (sportsFragment == null) { 
      try { 
       Thread.sleep(300); 
      } catch (InterruptedException e) { 
       System.out.println("Caught InterruptedException :" + e); 
      } 
     } 
     // Switches fragments to FavouriteFragment 
     ft.replace(R.id.content_fragment, sportsFragment, "Sports"); 
     // Noticeable delay here 
     ft.commit(); 
    } 
    ... 
    class InitialiseNavFrags extends Thread { 
     public void run() { 
      favouriteFragment = new FavouriteFragment(); 
      sportsFragment = new SportFragment(); 
     } 
    } 
} 

public class SportsFragment extends Fragment { 
    public View onCreateView (...) { 
     // Task with noticeable delay 
     return view; 
    } 
} 

我的问题是SportFragment小号selectItem执行的onCreateView直到MainActivity没有得到执行“和片段交换这会导致明显的延迟时用户按下导航项目。

那么,是否有可能初始化片段的视图,以便没有明显的延迟?

+1

你不应该在主UI线程上使用'Thread.sleep()'。您不应该在后台线程上创建这些片段,而是尝试改进错误的onCreateView()的onCreateView()(太多视图?)。 – Luksprog 2014-08-30 04:38:52

回答

0

在单独的线程上创建片段不是一个好主意;您应该优化OnCreateView

0

我还没有尝试过,但我想只能在onCreateView中膨胀一个容器,然后在后台线程中充注其他视图并在完成充气后将它们添加到该容器中。

我现在面临同样的问题。