Android-加载一个片段';在交换片段之前删除视图
我有一个活动,其中包含一个导航抽屉,当按下不同的导航项时,它会显示不同的片段。问题是其中一个片段在加载时有明显的延迟 在我的活动的Android-加载一个片段';在交换片段之前删除视图,android,android-fragments,Android,Android Fragments,我有一个活动,其中包含一个导航抽屉,当按下不同的导航项时,它会显示不同的片段。问题是其中一个片段在加载时有明显的延迟 在我的活动的onCreate方法中,我启动了一个线程,我想预加载每个片段,以便在用户按下导航项时可以轻松地交换它 我的代码如下所示: public class MainActivity extends Activity { protected void OnCreate { // Get instance of Thread InitialiseNavFr
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
的onCreateView
在执行MainActivity
的selectItem
并交换片段之前不会执行,这会在用户按下导航项时造成明显的延迟
那么,是否有可能初始化片段的视图,以便没有明显的延迟?在单独的线程上创建片段不是一个好主意;您应该改为优化OnCreateView。我还没有尝试过,但我想只可以在OnCreateView中充气一个容器,然后在后台线程中充气其他视图,并在充气完成后将其添加到该容器中
我现在面临着同样的问题。您不应该在主UI线程上使用
Thread.sleep()
。您不应该在后台线程上创建这些片段,而应该尝试改进错误的onCreateView()的onCreateView()
(视图太多?)。