Fragment的使用
![](https://images2018.cnblogs.com/blog/430354/201804/430354-20180429114409681-1528947448.png)
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>
<!-- 内容 结束 -->