Android使用ViewPager实现顶部tabbar切换界面
时间:2022-01-09 11:07:01|栏目:Android代码|点击: 次
类似的功能可以看看:
进入正题
效果图:
注: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) ?C》public void onCreate(@Nullable Bundle savedInstanceState) ?C》public View onCreateView ?C》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的写法和这个类似。
上一篇:Android自定义弹出窗口PopupWindow使用技巧
栏 目:Android代码
下一篇:eclipse中运行monkeyrunner脚本之环境搭建(4)
本文标题:Android使用ViewPager实现顶部tabbar切换界面
本文地址:http://www.codeinn.net/misctech/189615.html