Delay initialization when using Fragment in Android

前端 未结 1 1150
广开言路
广开言路 2020-12-21 14:47

When one fragment A is changed to another fragment B, it will call onCreate() and some other functions to do initialization. After the Fragment has

相关标签:
1条回答
  • 2020-12-21 15:43

    My Problem Is: some codes are very slow so I want to initialize a part of the datas instead of ALL of them.

    I hope you're not doing heavy operations on the main UI thread.

    How can I know the fragment is hide or its the current one? OR Can I get the content fragment in TabHost? OR Other ways to delay the initialization.

    You could use a trick regarding the FragmentPagerAdapter. In your onPageSelected method you could find out which is the current Fragment and call an initialization method on it:

    public void onPageSelected(int position) {
        //...
        Fragment item = getSupportFragmentManager().findFragmentByTag("android:switcher:" + R.id.theIdOfTheViewPager + ":" + position);
        if (item != null && item.getView() != null) {
            item.initializeStuffForThisFragment();// you need to cast it to your Fragment class 
        }
    }
    
    0 讨论(0)
提交回复
热议问题