阿神2017-04-18 09:06:57
強烈不建議這麼玩: 如果頁面很多, 而且又沒管理好
Fragment
, 那很有可能 OOM...
如果非要這樣玩, 請參考FragmentStatePagerAdapter
的管理方式. 關鍵代碼如下:
public abstract class FragmentStatePagerAdapter extends PagerAdapter {
@Override
public Object instantiateItem(ViewGroup container, int position) {
// If we already have this item instantiated, there is nothing
// to do. This can happen when we are restoring the entire pager
// from its saved state, where the fragment manager has already
// taken care of restoring the fragments we previously had instantiated.
if (mFragments.size() > position) {
Fragment f = mFragments.get(position);
if (f != null) {
return f;
}
}
if (mCurTransaction == null) {
mCurTransaction = mFragmentManager.beginTransaction();
}
Fragment fragment = getItem(position);
if (DEBUG) Log.v(TAG, "Adding item #" + position + ": f=" + fragment);
if (mSavedState.size() > position) {
Fragment.SavedState fss = mSavedState.get(position);
if (fss != null) {
fragment.setInitialSavedState(fss);
}
}
while (mFragments.size() <= position) {
mFragments.add(null);
}
fragment.setMenuVisibility(false);
fragment.setUserVisibleHint(false);
mFragments.set(position, fragment);
mCurTransaction.add(container.getId(), fragment);
return fragment;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
Fragment fragment = (Fragment) object;
if (mCurTransaction == null) {
mCurTransaction = mFragmentManager.beginTransaction();
}
if (DEBUG) Log.v(TAG, "Removing item #" + position + ": f=" + object
+ " v=" + ((Fragment)object).getView());
while (mSavedState.size() <= position) {
mSavedState.add(null);
}
mSavedState.set(position, fragment.isAdded()
? mFragmentManager.saveFragmentInstanceState(fragment) : null);
mFragments.set(position, null);
mCurTransaction.remove(fragment);
}
}
除此之外, Activity
有NavigateUp(向上導航) 和BackPressed(回退鍵) 的功能, 因此, 還要管理Activity
有 NavigateUp(向上导航) 和 BackPressed(回退键) 的功能, 因此, 还要管理Fragment
的回退栈(和Activity
的回退栈是不一样的), 即调用 FragmentTransaction#addToBackStack(String)
的回退棧(和Activity
的回退棧是不一樣的), 即呼叫FragmentTransaction#addToBackStack(String)
.
黄舟2017-04-18 09:06:57
建議同上面的回答一樣,盡量不要這樣搞。
希望你可以分析一下需要處理的幾個頁面,是否是同样性质
的。比如說網易新聞,不同頻道所展現的內容是類似的,所以使用Fragment比較適合。但設定項中,各設定項中內容比較獨立,使用不同的Activity比較好。