getSupportFragmentManager要用在FragmentActivity及其子類中!!
關於安卓抽屜導航!!
* 自定義側邊欄
創建一個Fragment:CarlozLibFragment.java,並為其創建一個布局carloz_lib_webview.xml,內部有一個WebView控件,順便在AndroidManifest.xml中添加Intent訪問權限;在CarlozLibFragment中重寫onCreateView方法,讓WebView訪問我的個人網站(http://carloz.duapp.com);
public class CarlozLibFragment extends Fragment { private String TAG = "CARLOZ"; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // TODO Auto-generated method stub View root = inflater.inflate(R.layout.carloz_lib_webview, container, false); WebView wv =(WebView)root.findViewById(R.id.wv); Log.d(TAG, "load url: carloz lib"); wv.loadUrl("http://carloz.duapp.com"); return root; } }
將NavigationDrawerFragment.java 中 onCreateView中ListView相關內容刪除,用自定義布局 diy_slider_content.xml (目錄res/layout)替換;diy_slider_content中定義了一個按鈕,用來打開剛剛創建的CarlozLibFragment;
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View root = inflater.inflate(R.layout.diy_slider_content, container, false); root.findViewById(R.id.btnJump).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (mDrawerLayout != null) { // 隱藏側邊欄 mDrawerLayout.closeDrawer(mFragmentContainerView); } if(mCallbacks != null) { mCallbacks.onGotoCarlozLibClicked(); } } }); return root; }
onGotoCarlozLibClicked()這個接口是自定義接口,在 靜態接口 NavigationDrawerCallbacks 中新增定義
public static interface NavigationDrawerCallbacks { /** * Called when an item in the navigation drawer is selected. */ void onNavigationDrawerItemSelected(int position); // 通過回調傳給主界面 void onGotoCarlozLibClicked(); }
需要在主界面SliderActivity中實現該回調方法, 因為主界面實現了 NavigationDrawerFragment.NavigationDrawerCallbacks 接口
@Override public void onGotoCarlozLibClicked() { // 需要實現 NavigationDrawerFragment.java Callback中新增的方法 // 在容器 container 中添加 fragment CarlozLibFragment getSupportFragmentManager().beginTransaction() .replace(R.id.container, new CarlozLibFragment()) .commit(); }
運行結果如下:
這裡引用:http://www.cnblogs.com/carlo/p/4726719.html