Android使用ViewPager实现顶部tabbar切换界面

类似的功能可以看看:

使用RadioGroup实现底部导航栏

进入正题

效果图:

注:PagerSlidingTabStrip为自定义控件,用于切换界面,此处不便贴出代码

1.主界面xml布局中添加ViewPager控件:

 <android.support.v4.view.ViewPager
  android:id="@+id/pager_view"
  android:layout_width="match_parent"
  android:layout_height="match_parent" />

2.主界面的activity代码:

FrOrderList和FrFoodList分别为内部的fragment页面

String[] tabs = {"坚果", "肉脯", "果冻"};
  private MyPagerAdpater adpater;

  //为ViewPager添加Adpater
  adpater = new MyPagerAdpater(getSupportFragmentManager());
  pagerView.setOffscreenPageLimit(4);
  pagerView.setAdapter(adpater);

class MyPagerAdpater extends FragmentPagerAdapter {

  public MyPagerAdpater(FragmentManager manager) {
   super(manager);
  }

  @Override
  public Fragment getItem(int position) {
   switch (position){
    case 0:
     return FrOrderList.newInstance( 0);
    case 1:
     return FrFoodList.newInstance( 1);
    case 2:
     return FrOrderList.newInstance( 2);
   }
   return null;
  }

  @Override
  public CharSequence getPageTitle(int position) {
   return tabs[position];
  }
  @Override
  public int getCount() {
   return tabs.length;
  }
 }

3.内部fragment页面:
其布局只是为了纯显示,所以只添加了一个textview

<TextView
  android:id="@+id/tv_content"
  android:gravity="center"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:textSize="32sp"
  android:textColor="#63B8FF"
  android:text="999"/>

activity代码:

整个流程为:

public static FrFoodList newInstance(int mState) 
–》public void onCreate(@Nullable Bundle savedInstanceState) 
–》public View onCreateView 
–》public void initView()

public class FrFoodList extends Fragment {

 TextView tvContent;

 private static String DATAKEY = "STATE";
 private int mState = 0;

 public static FrFoodList newInstance(int mState) {
 FrFoodList frFoodList = new FrFoodList();
 Bundle bundle = new Bundle();
 bundle.putInt( DATAKEY, mState);
 frFoodList.setArguments(bundle);
 return frFoodList;
 }

 @Override
 public void onCreate(@Nullable Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 mState = getArguments().getInt( DATAKEY);
 }

 @Nullable
 @Override
 public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
 View view = inflater.inflate(R.layout.fragment_food_list, null);
 tvContent = (TextView) view.findViewById(R.id.tv_content); 
 initView();
 return view;
 }

 public void initView(){
 switch ( mState ){
  case 0:
  tvContent.setText( "一大波坚果即将来袭~~~" );
  break;
  case 1:
  tvContent.setText( "好吃又香,美味抵挡不住(^_^)" );
  break;
  case 2:
  tvContent.setText( "浪漫气息,粉嫩可爱(*_*)" );
  break;
 }
 }
}

FrOrderList的写法和这个类似。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持鸟哥教程(niaoge.com)。

声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:notice#niaoge.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。