Fragment核心代碼:
/**
* 切換Fragment
* <p>
* 切換Fragment
* </p>
*
* @param Class
* <? extends Fragment> c
* @return 無
* @throws 無
*/
public void toggleFragment(Class<? extends Fragment> currentFragment) {
FragmentManager manager = getSupportFragmentManager();
String strCurrentFragmentName = currentFragment.getName();
FragmentTransaction transaction = manager.beginTransaction();
Fragment fragment = manager.findFragmentByTag(strCurrentFragmentName);
if (fragment == null) {
try {
fragment = currentFragment.newInstance();
// 替換時保留Fragment,以便複用
transaction.add(R.id.content_frame, fragment,
strCurrentFragmentName);
} catch (Exception e) {
// ignore
}
}
// 遍歷存在的Fragment,隱藏其餘Fragment
List<Fragment> fragments = manager.getFragments();
if (fragments != null)
for (Fragment fm : fragments)
if (!fm.equals(fragment))
transaction.hide(fm);
transaction.show(fragment);
transaction.commit();
}
解釋:
transaction.add(R.id.content_frame, fragment,
strCurrentFragmentName);
把fragment 填充到「content_frame」
佈局文件:
<!-- 內容 開始 -->
<FrameLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" >
<FrameLayout
android:id="@+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_gravity="bottom"
android:background="@drawable/tab_shadow" />
</FrameLayout>
<!-- 內容 結束 -->