getSupportFragmentManager() 必須在 FragmentActivity 及其子類中調用。本文通過自定義側邊欄按鈕點擊動態替換 Fragment 演示正確用法。
CarlozLibFragment 包含 WebView,onCreateView 加載個人網站。NavigationDrawerFragment 使用自定義佈局 diy_slider_content.xml,含按鈕 btnJump。NavigationDrawerFragment 內部接口 NavigationDrawerCallbacks 新增 onGotoCarlozLibClicked()。SliderActivity implements NavigationDrawerCallbacks,在回調中切換 Fragment。root.findViewById(R.id.btnJump).setOnClickListener(v -> {
if (mDrawerLayout != null) mDrawerLayout.closeDrawer(mFragmentContainerView);
if (mCallbacks != null) mCallbacks.onGotoCarlozLibClicked();
});
public static interface NavigationDrawerCallbacks {
void onNavigationDrawerItemSelected(int position);
void onGotoCarlozLibClicked(); // 新增
}
@Override
public void onGotoCarlozLibClicked() {
getSupportFragmentManager().beginTransaction()
.replace(R.id.container, new CarlozLibFragment())
.commit();
}
FragmentActivity(或 AppCompatActivity),才能調用 getSupportFragmentManager()。beginTransaction() → replace(containerId, fragment) → commit()。DrawerLayout.closeDrawer(view)。