标签:
参考:慕课网《Android攻城狮的第二门课》
在完成NaviActivity之前,先把需要使用的一个重要控件ViewPager学习一下。
(1)使用view作为数据源:
1 private List<View> viewList; 2 private ViewPager pager; 3 private PagerTabStrip tab; 4 5 protected void onCreate(Bundle savedInstanceState) { 6 super.onCreate(savedInstanceState); 7 setContentView(R.layout.activity_navi); 8 Intent oldpager = getIntent(); 9 int num = oldpager.getIntExtra("Authorization", 0); 10 viewList = new ArrayList<View>(); 11 /** 12 * 通过View对象去作为ViewPager的数据源 13 */ 14 View firstView, secondView; 15 titleList = new ArrayList<String>(); 16 firstView = View.inflate(this, R.layout.activity_machine_inquiry, null); 17 titleList.add("机器查询"); 18 if (num == 0) { 19 secondView = View.inflate(this, R.layout.activity_stu_info, null); 20 //为ViewPager页卡设置标题 21 titleList.add("用户信息"); 22 }else{ 23 secondView = View.inflate(this, R.layout.activity_stu_inquiry, null); 24 titleList.add("学生查询"); 25 } 26 viewList.add(firstView); 27 viewList.add(secondView); 28 29 //为PagerTabStrip设置一些属性 30 tab = (PagerTabStrip) findViewById(R.id.stuTab); 31 tab.setBackgroundColor(Color.YELLOW); 32 tab.setTextColor(Color.RED); 33 tab.setDrawFullUnderline(false); 34 tab.setTabIndicatorColor(Color.GREEN); 35 36 //初始化ViewPager 37 pager = (ViewPager) findViewById(R.id.stuPager); 38 39 //创建PagerAdapter的适配器 40 MyPagerAdapter adapter = new MyPagerAdapter(viewList, titleList); 41 42 //ViewPager加载适配器 43 pager.setAdapter(adapter); 44 } 45 }
1 package com.example.wanderingzj.stumanage; 2 3 import android.support.v4.view.PagerAdapter; 4 import android.view.View; 5 import android.view.ViewGroup; 6 7 import java.util.List; 8 9 /** 10 * Created by samsung on 2015/10/28. 11 */ 12 public class MyPagerAdapter extends PagerAdapter { 13 private List<View> viewList; 14 private List<String> titleList; 15 16 public MyPagerAdapter(List<View> viewList, List<String> titleList){ 17 this.viewList = viewList; 18 this.titleList = titleList; 19 } 20 21 /** 22 * 返回页卡数量 23 * @return 24 */ 25 @Override 26 public int getCount() { 27 return viewList.size(); 28 } 29 30 /** 31 * View是否来自于对象 32 * @param arg0 33 * @param arg1 34 * @return 35 */ 36 @Override 37 public boolean isViewFromObject(View arg0, Object arg1) { 38 return arg0 == arg1; 39 } 40 41 /** 42 * 实例化一个页卡 43 * @param container 44 * @param position 45 * @return 46 */ 47 @Override 48 public Object instantiateItem(ViewGroup container, int position) { 49 container.addView(viewList.get(position)); 50 return viewList.get(position); 51 } 52 53 /** 54 * 销毁一个页卡 55 * @param container 56 * @param position 57 * @param object 58 */ 59 @Override 60 public void destroyItem(ViewGroup container, int position, Object object) { 61 container.removeView(viewList.get(position)); 62 } 63 64 /** 65 * 设置ViewPager页卡标题 66 * @param position 67 * @return 68 */ 69 @Override 70 public CharSequence getPageTitle(int position) { 71 return titleList.get(position); 72 } 73 }
标签:
原文地址:http://www.cnblogs.com/wanderingzj/p/4930614.html