欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

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

程序员文章站 2023-12-12 13:54:16
类似的功能可以看看: 使用radiogroup实现底部导航栏 进入正题 效果图: 注:pagerslidingtabstrip为自定义控件,用于切...

类似的功能可以看看:

使用radiogroup实现底部导航栏

进入正题

效果图:

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

注: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的写法和这个类似。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

上一篇:

下一篇: