FragmentPagerAdapter 更新數據遇到了坑啊。下拉刷新不會更新頁面、有緩存。

ViewPager+FragmentPagerAdapter:

更新Fragment裏數據是不起作用,FragmentPagerAdapter添加或減少Fragment時,前面的Fragment內容更新不起作用等等問題,有的做法是暴力刪除fragment列表

粗暴解決方案1:

List<Fragment> fragments = getSupportFragmentManager().getFragments();
for (int i = fragments.size() - 1; i >= 0; i--) {
getSupportFragmentManager().beginTransaction().remove(fragments.get(0));
}


粗暴解決方案2:

    @Override
public Object instantiateItem(ViewGroup container, int position) {
    if (mCurTransaction == null) {
        mCurTransaction = mFragmentManager.beginTransaction();
    }

    final long itemId = getItemId(position);

    // Do we already have this fragment?
    String name = makeFragmentName(container.getId(), itemId);
    Fragment fragment = mFragmentManager.findFragmentByTag(name);
    if (fragment != null) {
        if (DEBUG) Log.v(TAG, "Attaching item #" + itemId + ": f=" + fragment);
        mCurTransaction.attach(fragment);
    } else {
        fragment = getItem(position);
        if (DEBUG) Log.v(TAG, "Adding item #" + itemId + ": f=" + fragment);
        mCurTransaction.add(container.getId(), fragment,
                makeFragmentName(container.getId(), itemId));
    }
    if (fragment != mCurrentPrimaryItem) {
        fragment.setMenuVisibility(false);
        fragment.setUserVisibleHint(false);
    }

    return fragment;
} 
@Override
public long getItemId(int position) {
    // 獲取當前數據的hashCode
    int hashCode = fragments.get(position).hashCode();
    return hashCode;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章