系统自带的NavigationDrawerFragment
1、自动生成NavigationDrawerFragment,onCreatView代码如下
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mDrawerListView = (ListView) inflater.inflate( R.layout.fragment_navigation_drawer, container, false); View headerView = inflater.inflate(R.layout.fragment_navigation_drawer_header, null); mDrawerListView.addHeaderView(headerView); mDrawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { selectItem(position); } }); List<DrawerListItem> drawerdata = new ArrayList<DrawerListItem>(); DrawerListItem item = new DrawerListItem(getResources().getDrawable(R.drawable.title_timer_data) ,getResources().getString(R.string.title_timer_data)); drawerdata.add(item); item = new DrawerListItem(getResources().getDrawable(R.drawable.title_history_data) ,getResources().getString(R.string.title_history_data)); drawerdata.add(item); item = new DrawerListItem(getResources().getDrawable(R.drawable.title_history_chart) ,getResources().getString(R.string.title_history_chart)); drawerdata.add(item); item = new DrawerListItem(getResources().getDrawable(R.drawable.title_alarm_data) ,getResources().getString(R.string.title_alarm_data)); drawerdata.add(item); item = new DrawerListItem(getResources().getDrawable(R.drawable.title_setting) ,getResources().getString(R.string.title_setting)); drawerdata.add(item); selectItem(mCurrentSelectedPosition); DrawerListAdapter adapter = new DrawerListAdapter(this.getActivity(),drawerdata); mDrawerListView.setAdapter(adapter); // mDrawerListView.setAdapter(new ArrayAdapter<String>( // getActionBar().getThemedContext(), // android.R.layout.simple_list_item_activated_1, // android.R.id.text1, // new String[]{ // getString(R.string.title_timer_data), // getString(R.string.title_history_data), // getString(R.string.title_history_chart), // getString(R.string.title_alarm_data), // getString(R.string.title_setting), // })); mDrawerListView.setItemChecked(mCurrentSelectedPosition, true); return mDrawerListView; }
2、主界面选择标题,调用Fragment
/** *获取fragment */ public void onSectionAttached(int number) { Fragment fragment = null; switch (number) { case 1: fragment = new TimerDataFragment(); mTitle = getString(R.string.title_timer_data); break; case 2: mTitle = getString(R.string.title_history_data); break; case 3: mTitle = getString(R.string.title_history_chart); break; case 4: mTitle = getString(R.string.title_alarm_data); break; case 5: mTitle = getString(R.string.title_setting); break; default: break; } if (fragment != null) { //FragmentManager fragmentManager = getSupportFragmentManager(); FragmentManager fragmentManager = getFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.replace(R.id.container, fragment); fragmentTransaction.commit(); } }