亲宝软件园·资讯

展开

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

An_nAl 人气:0
想了解Android使用ViewPager实现顶部tabbar切换界面的相关内容吗,An_nAl在本文为您仔细讲解ViewPager实现顶部tabbar切换界面的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点: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的写法和这个类似。

加载全部内容

相关教程
猜你喜欢
用户评论