2014-04-17 87 views
10

我有一個ViewPager,它的片段中包含幾個TextView,它們具有不同的字體大小。 此外,我得到增加/減少字體大小的按鈕,通過添加其默認大小加上一個名爲STEP(它通過增量/減去字體大小按鈕更改)的值來計算每個textView的字體大小。
我的問題是如果應用大小更改後首次顯示視圖,它將在onCreateView()期間創建期望大小的textViews,但是如果片段已被緩存且onCreateView不會再次調用,我不知道如何更新他們的文本視圖只考慮一個緩存片段在屏幕上顯示(我可以更新它沒有問題),但其他人不顯示(我不知道他們是否附加到活動或在這種情況下)。
換句話說,我該如何檢測哪些片段被ViewPager及其已調用的onCreateView緩存(這些是必須更新其視圖的片段)。我標誌着他們在淺綠色,並在下面的圖片問號:enter image description hereAndroid ViewPager:在ViewPager中更新屏幕外但緩存的片段

回答

9

爲了通過ViewPager有緩存的項目清單我改變了我的自定義適配器,其延伸FragmentStatePagerAdapter:

  1. 添加HashMap<Integer, FragmentDipsplayPageContent> cachedFragmentHashMap到我的適配器
  2. 更新的getItem()方法,這樣

    public Fragment getItem(int index) {   
        Fragment fragment = new FragmentDipsplayPageContent(); 
        Bundle args = new Bundle(); 
        args.putInt("INDEX", index); 
        fragment.setArguments(args); 
        cachedFragmentHashMap.put(index,fragment); 
        return fragment; 
    } 
    
  3. 更新destroyItem()這樣的

    @Override 
    public void destroyItem(ViewGroup container, int position, Object object) { 
        super.destroyItem(container, position, object); 
        //add this line to remove fragments wiped from ViewPager cache 
        cachedFragmentHashMap.remove(position); 
    } 
    
  4. 適配器的方法添加一個getter從活動訪問緩存片段的HashMap的:

    public HashMap<Integer, FragmentDipsplayPageContent> getCachedFragmentHashMap() { 
        return cachedFragmentHashMap; 
    } 
    
  5. 更新中使用這個集合活動:

    private void increaseFontSizeForCachedFragments() { 
        HashMap<Integer, FragmentDipsplayPageContent> cachedFragmentsHashMap = adapterViewPager 
          .getCachedFragmentHashMap(); 
        Collection<FragmentDipsplayPageContent> fragmentsCollection = cachedFragmentsHashMap 
          .values(); 
        for (FragmentDipsplayPageContent fragmentDipsplayPageContent : fragmentsCollection) { 
         //update views of fragment 
         fragmentDipsplayPageContent.increasTextFontSize(); 
        } 
    } 
    


    這樣,所有包含可見和不在屏幕片段的緩存片段都會更新。

7

使用FragmentStatePagerAdapter而不是FragmentPagerAdapterViewPager適配器

+0

我目前使用FragmentStatePagerAdapter。 – VSB

+0

好,那對我有用,節省了我的時間。 非常感謝! – mohnage7

+0

客戶端正在使用傳呼機,就像她在玩遊戲..它在網上載入相當數量的數據,因此它在30頁以後被掛起。 .. 感謝您的解決方案。 –

22

接受的答案是好的,但你不應該緩存所有的項目。相反,你可以使用這種方法:

mViewPager.setOffscreenPageLimit(int); 

例如,有許多項目的圖像和動畫。如果你緩存所有這些,這可能會導致一個OutOfMemoryError。爲了防止,您可以定義要緩存的頁面限制。

編輯:而不是HashMap<Integer, Object>,最好使用SparseArray<Object>

+2

問題是如何啓用緩存,但可以在不可見時訪問緩存項目以進行更新。 – VSB

+0

什麼是默認大小? – Relm

+0

如果你使用這個解決方案你如何刪除緩存中的屏幕?我現在有這個問題導致緩存頁不更新。 –