你的位置:首页 > 操作系统

[操作系统]Android典型界面设计 ——DrawerLayout+Fragement+ViewPager+PagerTabStrip实现双导航

一、问题描述

  在Android典型界面设计(3)的我们实现了双导航效果,即外层底部导航和内部区域的头部导航,如网易新闻等很多应用采用了这种导航,但Google提供DrawerLayout可实现抽屉式导航,建议使用DrawerLayout代替底部导航,下面我们就使用官方提供的DrawerLayout+Fragement+ViewPager+PagerTabStrip实现下图效果:

二、本例相关技术

1、 DrawerLayout 抽屉式导航

2、 Fragment管理

3、 ViewPager和PagerTabStrip的使用

三、实现过程

  1、  考虑到向下兼容要使用V4和V7包

  V4建工程已经加入,需在项目中导入v7兼容包的android-support-v7-appcompat

  2、  MainActivity组件

  先看一下布局文件

<android.support.v4.widget.DrawerLayout  ="http://schemas.android.com/apk/res/android"  android:id="@+id/drawer_layout"  android:layout_width="match_parent"  android:layout_height="match_parent">  <!-- 包含主要内容的 view -->  <FrameLayout    android:id="@+id/content_frame"    android:layout_width="match_parent"    android:layout_height="match_parent" />  <!-- navigation drawer(抽屉式导航) -->  <ListView android:id="@+id/left_drawer"    android:layout_width="240dp"    android:layout_height="match_parent"    android:layout_gravity="start"    android:choiceMode="singleChoice"    android:divider="@android:color/transparent"    android:dividerHeight="0dp"    android:background="#fff"/></android.support.v4.widget.DrawerLayout>

  DrawerLayout有两个子视图(child view):一个FrameLayout用来包含主要内容(在运行时填入Fragment),和一个navigation drawer这里使用的ListView。

navigation drawer部分必须使用android:layout_gravity属性指定它的horizontal gravity

“start”表示左侧,”end”表示右侧

  3、  MainActivity代码:

public class MainActivity extends ActionBarActivity implements OnItemClickListener{  private DrawerLayout drawerLayout;  private ActionBarDrawerToggle toggle;  private ListView navList;  private FragmentManager fm;  private List<Fragment> fragments;  private ArrayAdapter<String> adapter;  private ActionBar actionBar;  @Override  protected void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.activity_main);    drawerLayout=(DrawerLayout)super.findViewById(R.id.drawer_layout);    navList=(ListView)super.findViewById(R.id.left_drawer);    navList.setOnItemClickListener(this);    fragments=new ArrayList<Fragment>();    fm=super.getSupportFragmentManager();    initListView();    initActionBar();    initDrawerLayout();    initFragments();  }      private String[] tabs=new String[]{"新闻","阅读 ","视听","发现","我的设置 "};    /**  初始化drawer的item列表。这要根据你的app内容来处理,但是一个navigation drawer通常由一个ListView组成,所以列表应该通过一个Adapter填入。*/  private void initListView(){    adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,        tabs);    navList.setAdapter(adapter);  }  private void initFragments(){    NewsFragment newsFragment=new NewsFragment();    fragments.add(newsFragment);    ReadFragment readFragment=new ReadFragment();    fragments.add(readFragment);    VideoFragment videoFragment=new VideoFragment();    fragments.add(videoFragment);    FoundFragment foundFragment=new FoundFragment();    fragments.add(foundFragment);    OwnerFragment ownerFragment=new OwnerFragment();    fragments.add(ownerFragment);    setFragments(0);  }  private void setFragments(int position){    fm.beginTransaction().replace(R.id.content_frame,         fragments.get(position),"t"+position).commit();  }  private void initActionBar(){    actionBar=super.getSupportActionBar();    actionBar.setDisplayHomeAsUpEnabled(true);    actionBar.setIcon(new ColorDrawable(0));    actionBar.setTitle(tabs[0]);    }  private void initDrawerLayout(){    toggle=new ActionBarDrawerToggle(this, drawerLayout,         R.drawable.com_btn, R.string.drawer_open,        R.string.drawer_closed){          /** 当drawer处于完全关闭的状态时调用 */          @Override          public void onDrawerClosed(View drawerView) {            super.onDrawerClosed(drawerView);          }            /** 当drawer处于完全打开的状态时调用 */          @Override          public void onDrawerOpened(View drawerView) {            super.onDrawerOpened(drawerView);          }          };    // 设置drawer触发器为DrawerListener    drawerLayout.setDrawerListener(toggle);  }  private void toggleNav(){    if(drawerLayout.isDrawerOpen(Gravity.START)){      drawerLayout.closeDrawer(Gravity.START);    }else{      drawerLayout.openDrawer(Gravity.START);    }      }  @Override  public boolean onCreateOptionsMenu(Menu menu) {        getMenuInflater().inflate(R.menu.main, menu);    return true;  } @Override  public boolean onOptionsItemSelected(MenuItem item){   switch(item.getItemId()){     case android.R.id.home:     toggleNav();     break;   }   return true; }

  4、  NewsFragment组件

public class NewsFragment extends Fragment {  private ViewPager mViewPager;  private List<String> tabs;  private List<Fragment> fragmentList;  private NewsFragmentPagerAdapter adapter;  @Override  public void onActivityCreated(Bundle savedInstanceState) {    // TODO Auto-generated method stub    super.onActivityCreated(savedInstanceState);  }  @Override  public void onCreate(Bundle savedInstanceState) {    // TODO Auto-generated method stub    super.onCreate(savedInstanceState);  }  private View view;  @Override  public View onCreateView(LayoutInflater inflater, ViewGroup container,      Bundle savedInstanceState) {    if(view==null){      view=inflater.inflate(R.layout.news_fragment, null);      mViewPager=(ViewPager)view.findViewById(R.id.pager);      initViewPager();    }    ViewGroup parent=(ViewGroup)view.getParent();    if(parent!=null) parent.removeView(view);    return view;  }  private void initViewPager(){    setTabs();    setFragments();    adapter=new NewsFragmentPagerAdapter(super.getActivity().getSupportFragmentManager(),         fragmentList, tabs);    mViewPager.setAdapter(adapter);  }    private void setFragments(){    fragmentList=new ArrayList<Fragment>();    for(int i=0;i<tabs.size();i++){      NewsChannelFragment fragment=new NewsChannelFragment();      Bundle bundle=new Bundle();      bundle.putString("title", tabs.get(i)+"区域");      fragment.setArguments(bundle);      fragmentList.add(fragment);          }  }  private void setTabs(){    tabs=new ArrayList<String>();    tabs.add("头条");    tabs.add("娱乐");    tabs.add("体育");    tabs.add("财经");    tabs.add("热点");    tabs.add("科技");  }  @Override  public void onDestroyView() {    // TODO Auto-generated method stub    super.onDestroyView();  }}

NewsFragment的布局文件:

<android.support.v4.view.ViewPager    ="http://schemas.android.com/apk/res/android"    android:id="@+id/pager"    android:layout_width="match_parent"    android:layout_height="match_parent">  <android.support.v4.view.PagerTabStrip    android:id="@+id/pager_tab_strip"    android:layout_width="match_parent"    android:layout_height="wrap_content"    android:layout_gravity="top"    android:background="#33b5e5"    android:textColor="#fff"    android:paddingTop="4dp"    android:paddingBottom="4dp" /></android.support.v4.view.ViewPager>

NewsFragmentPagerAdapter代码:

public class NewsFragmentPagerAdapter extends FragmentPagerAdapter {  private List<String> tabs;  private List<Fragment> fragmentList;  public NewsFragmentPagerAdapter(FragmentManager fm,List<Fragment> fragmentList,List<String> tabs) {    super(fm);    this.tabs=tabs;    this.fragmentList=fragmentList;      }  @Override  public Fragment getItem(int idx) {    return fragmentList.get(idx);  }  @Override  public int getCount() {    return fragmentList.size();  }  @Override  public CharSequence getPageTitle(int position) {    return tabs.get(position);  }}

  5、  ReadFragment代码(其他Fragment也简单处理同ReadFragment基本相同)

public class ReadFragment extends Fragment {  @Override  public void onAttach(Activity activity) {    // TODO Auto-generated method stub    super.onAttach(activity);  }  @Override  public View onCreateView(LayoutInflater inflater, ViewGroup container,    Bundle savedInstanceState) {    TextView tvTitle=new TextView(super.getActivity());    tvTitle.setText("阅读");    tvTitle.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT));    tvTitle.setBackgroundColor(Color.WHITE);    return tvTitle;  }  @Override  public void setArguments(Bundle args) {    // TODO Auto-generated method stub    super.setArguments(args);  }}

6、样式文件values/styles.xm 

  <style name="AppTheme" parent="@style/Theme.AppCompat.Light">    <item name="actionBarStyle">@style/ActionBar.Solid</item>    <item name="homeAsUpIndicator">@drawable/com_btn</item>     <item name="titleTextStyle">@style/ActionBar_TitleStyle</item>  </style>  <style name="ActionBar.Solid" parent="@style/Widget.AppCompat.Light.ActionBar.Solid">    <item name="android:background">@drawable/ab_background</item>    <item name="backgroundSplit">@drawable/ab_bottom_solid</item>    </style>     <style name="ActionBar_TitleStyle">     <item name="android:textSize">18sp</item>    <item name="android:textColor">#ffffff</item> </style>values-v14/styles.<style name="AppBaseTheme" parent="android:Theme.Holo.Light.DarkActionBar">  </style> <style name="AppTheme" parent="@style/Theme.AppCompat.Light">    <item name="android:actionBarStyle">@style/ActionBar.Solid</item>    <item name="android:homeAsUpIndicator">@drawable/com_btn</item>     </style>  <style name="ActionBar.Solid" parent="@style/Widget.AppCompat.Light.ActionBar.Solid">    <item name="android:background">@drawable/ab_background</item>    <item name="android:backgroundSplit">@drawable/ab_bottom_solid</item>    <item name="android:titleTextStyle">@style/ActionBar_TitleStyle</item>  </style>   <style name="ActionBar_TitleStyle">     <item name="android:textSize">18sp</item>    <item name="android:textColor">#ffffff</item>   </style>

 

  想要了解更多内容的小伙伴,可以点击查看源码,亲自运行测试。

  疑问咨询或技术交流,请加入官方QQ群:JRedu技术交流 (452379712)

 

作者:杰瑞教育
出处:http://www.cnblogs.com/jerehedu/ 
本文版权归烟台杰瑞教育科技有限公司和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。