ViewPager 详解(四)----自主实现滑动指示条 - harvic - 博客频道 - CSDN.NET
前言:前面我们用了三篇的时间讲述了有关ViewPager的基础知识,到这篇就要进入点实际的了。在第三篇《ViewPager 详解(三)---PagerTabStrip与PagerTitleStrip添加标题栏的异同》中,我们说了,PagerTabStrip和PagerTitleStrip都不适合用在实际用途中,当要在实际运用中,我们就要自己去实现相关的功能。这篇文章中单纯讲述划动指示条的实现方法,而对于交互Tab的实现,就不再讲解,最后给出网上的一段源码,大家可以去研究一下,有关交互Tab的实现原理是一样的,难度不大。
相关文章:
3、《ViewPager 详解(三)---PagerTabStrip与PagerTitleStrip添加标题栏的异同》
4、《ViewPager 详解(四)----自主实现滑动指示条》
5、《ViewPager 详解(五)-----使用Fragment实现ViewPager滑动》
先上本篇效果图:
一、XML布局
布局代码如下:
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical"
- tools:context="com.example.testviewpage_2.MainActivity" >
- <ImageView
- android:id="@+id/cursor"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:scaleType="matrix"
- android:src="@drawable/a" />
- <android.support.v4.view.ViewPager
- android:id="@+id/viewpager"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_gravity="center"/>
- </LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context="com.example.testviewpage_2.MainActivity" > <ImageView android:id="@+id/cursor" android:layout_width="fill_parent" android:layout_height="wrap_content" android:scaleType="matrix" android:src="@drawable/a" /> <android.support.v4.view.ViewPager android:id="@+id/viewpager" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center"/> </LinearLayout>采用线性垂直布局,在滑动页面的上方添加一个小水平条。
二、JAVA代码
本例代码是根据《ViewPager 详解(一)---基本入门》 更改而来。
先给出全部代码,然后再逐步讲解。
- public class MainActivity extends Activity {
- private View view1, view2, view3;
- private List<View> viewList;// view数组
- private ViewPager viewPager; // 对应的viewPager
- private ImageView cursor;
- private int bmpw = 0; // 游标宽度
- private int offset = 0;// // 动画图片偏移量
- private int currIndex = 0;// 当前页卡编号
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- viewPager = (ViewPager) findViewById(R.id.viewpager);
- LayoutInflater inflater = getLayoutInflater();
- view1 = inflater.inflate(R.layout.layout1, null);
- view2 = inflater.inflate(R.layout.layout2, null);
- view3 = inflater.inflate(R.layout.layout3, null);
- viewList = new ArrayList<View>();// 将要分页显示的View装入数组中
- viewList.add(view1);
- viewList.add(view2);
- viewList.add(view3);
- //初始化指示器位置
- initCursorPos();
- viewPager.setAdapter(new MyPagerAdapter(viewList));
- viewPager.setOnPageChangeListener(new MyPageChangeListener());
- }
- //初始化指示器位置
- public void initCursorPos() {
- // 初始化动画
- cursor = (ImageView) findViewById(R.id.cursor);
- bmpw = BitmapFactory.decodeResource(getResources(), R.drawable.a)
- .getWidth();// 获取图片宽度
- DisplayMetrics dm = new DisplayMetrics();
- getWindowManager().getDefaultDisplay().getMetrics(dm);
- int screenW = dm.widthPixels;// 获取分辨率宽度
- offset = (screenW / viewList.size() - bmpw) / 2;// 计算偏移量
- Matrix matrix = new Matrix();
- matrix.postTranslate(offset, 0);
- cursor.setImageMatrix(matrix);// 设置动画初始位置
- }
- //页面改变监听器
- public class MyPageChangeListener implements OnPageChangeListener {
- int one = offset * 2 + bmpw;// 页卡1 -> 页卡2 偏移量
- int two = one * 2;// 页卡1 -> 页卡3 偏移量
- @Override
- public void onPageSelected(int arg0) {
- Animation animation = null;
- switch (arg0) {
- case 0:
- if (currIndex == 1) {
- animation = new TranslateAnimation(one, 0, 0, 0);
- } else if (currIndex == 2) {
- animation = new TranslateAnimation(two, 0, 0, 0);
- }
- break;
- case 1:
- if (currIndex == 0) {
- animation = new TranslateAnimation(offset, one, 0, 0);
- } else if (currIndex == 2) {
- animation = new TranslateAnimation(two, one, 0, 0);
- }
- break;
- case 2:
- if (currIndex == 0) {
- animation = new TranslateAnimation(offset, two, 0, 0);
- } else if (currIndex == 1) {
- animation = new TranslateAnimation(one, two, 0, 0);
- }
- break;
- }
- currIndex = arg0;
- animation.setFillAfter(true);// True:图片停在动画结束位置
- animation.setDuration(300);
- cursor.startAnimation(animation);
- }
- @Override
- public void onPageScrolled(int arg0, float arg1, int arg2) {
- }
- @Override
- public void onPageScrollStateChanged(int arg0) {
- }
- }
- /**
- * ViewPager适配器
- */
- public class MyPagerAdapter extends PagerAdapter {
- public List<View> mListViews;
- public MyPagerAdapter(List<View> mListViews) {
- this.mListViews = mListViews;
- }
- @Override
- public boolean isViewFromObject(View arg0, Object arg1) {
- // TODO Auto-generated method stub
- return arg0 == arg1;
- }
- @Override
- public int getCount() {
- // TODO Auto-generated method stub
- return mListViews.size();
- }
- @Override
- public void destroyItem(ViewGroup container, int position, Object object) {
- // TODO Auto-generated method stub
- container.removeView(mListViews.get(position));
- }
- @Override
- public Object instantiateItem(ViewGroup container, int position) {
- // TODO Auto-generated method stub
- container.addView(mListViews.get(position));
- return mListViews.get(position);
- }
- }
- }
public class MainActivity extends Activity { private View view1, view2, view3; private List<View> viewList;// view数组 private ViewPager viewPager; // 对应的viewPager private ImageView cursor; private int bmpw = 0; // 游标宽度 private int offset = 0;// // 动画图片偏移量 private int currIndex = 0;// 当前页卡编号 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); viewPager = (ViewPager) findViewById(R.id.viewpager); LayoutInflater inflater = getLayoutInflater(); view1 = inflater.inflate(R.layout.layout1, null); view2 = inflater.inflate(R.layout.layout2, null); view3 = inflater.inflate(R.layout.layout3, null); viewList = new ArrayList<View>();// 将要分页显示的View装入数组中 viewList.add(view1); viewList.add(view2); viewList.add(view3); //初始化指示器位置 initCursorPos(); viewPager.setAdapter(new MyPagerAdapter(viewList)); viewPager.setOnPageChangeListener(new MyPageChangeListener()); } //初始化指示器位置 public void initCursorPos() { // 初始化动画 cursor = (ImageView) findViewById(R.id.cursor); bmpw = BitmapFactory.decodeResource(getResources(), R.drawable.a) .getWidth();// 获取图片宽度 DisplayMetrics dm = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(dm); int screenW = dm.widthPixels;// 获取分辨率宽度 offset = (screenW / viewList.size() - bmpw) / 2;// 计算偏移量 Matrix matrix = new Matrix(); matrix.postTranslate(offset, 0); cursor.setImageMatrix(matrix);// 设置动画初始位置 } //页面改变监听器 public class MyPageChangeListener implements OnPageChangeListener { int one = offset * 2 + bmpw;// 页卡1 -> 页卡2 偏移量 int two = one * 2;// 页卡1 -> 页卡3 偏移量 @Override public void onPageSelected(int arg0) { Animation animation = null; switch (arg0) { case 0: if (currIndex == 1) { animation = new TranslateAnimation(one, 0, 0, 0); } else if (currIndex == 2) { animation = new TranslateAnimation(two, 0, 0, 0); } break; case 1: if (currIndex == 0) { animation = new TranslateAnimation(offset, one, 0, 0); } else if (currIndex == 2) { animation = new TranslateAnimation(two, one, 0, 0); } break; case 2: if (currIndex == 0) { animation = new TranslateAnimation(offset, two, 0, 0); } else if (currIndex == 1) { animation = new TranslateAnimation(one, two, 0, 0); } break; } currIndex = arg0; animation.setFillAfter(true);// True:图片停在动画结束位置 animation.setDuration(300); cursor.startAnimation(animation); } @Override public void onPageScrolled(int arg0, float arg1, int arg2) { } @Override public void onPageScrollStateChanged(int arg0) { } } /** * ViewPager适配器 */ public class MyPagerAdapter extends PagerAdapter { public List<View> mListViews; public MyPagerAdapter(List<View> mListViews) { this.mListViews = mListViews; } @Override public boolean isViewFromObject(View arg0, Object arg1) { // TODO Auto-generated method stub return arg0 == arg1; } @Override public int getCount() { // TODO Auto-generated method stub return mListViews.size(); } @Override public void destroyItem(ViewGroup container, int position, Object object) { // TODO Auto-generated method stub container.removeView(mListViews.get(position)); } @Override public Object instantiateItem(ViewGroup container, int position) { // TODO Auto-generated method stub container.addView(mListViews.get(position)); return mListViews.get(position); } } }从易到难一步步来讲。
1、MyPagerAdapter类
在前几篇中,我们对于适配器的实现总是new一个PageAdapter的实例。我们这里做了一点稍微的更改,将其集合成一个类,内容都没变,只是多了一个构造函数而已。所以针对这个类的具体代码,我就不再细讲,如果对其中的复写的函数为什么要这么写不理解的同学,请看《ViewPager 详解(二)---详解四大函数》
2、initCursorPos()---初始化指示器位置
游标在初始化显示时,我们要根据屏幕宽度来显示游标位置。先看看这部分代码:
- //初始化指示器位置
- public void initCursorPos() {
- // 初始化动画
- cursor = (ImageView) findViewById(R.id.cursor);
- bmpw = BitmapFactory.decodeResource(getResources(), R.drawable.a)
- .getWidth();// 获取图片宽度
- DisplayMetrics dm = new DisplayMetrics();
- getWindowManager().getDefaultDisplay().getMetrics(dm);
- int screenW = dm.widthPixels;// 获取分辨率宽度
- offset = (screenW / viewList.size() - bmpw) / 2;// 计算偏移量
- Matrix matrix = new Matrix();
- matrix.postTranslate(offset, 0);
- cursor.setImageMatrix(matrix);// 设置动画初始位置
- }
//初始化指示器位置 public void initCursorPos() { // 初始化动画 cursor = (ImageView) findViewById(R.id.cursor); bmpw = BitmapFactory.decodeResource(getResources(), R.drawable.a) .getWidth();// 获取图片宽度 DisplayMetrics dm = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(dm); int screenW = dm.widthPixels;// 获取分辨率宽度 offset = (screenW / viewList.size() - bmpw) / 2;// 计算偏移量 Matrix matrix = new Matrix(); matrix.postTranslate(offset, 0); cursor.setImageMatrix(matrix);// 设置动画初始位置 }可能有些同学不明白的位置在于,初始化位置的偏移量为什么这么算,下面,我画了张图,看下就应该明白了。
最后对于偏移的方法,可用的很多,这里仿网上的代码用了matrix;当然大家可以用其它的偏移方法,一样。
3、MyPageChangeListener()---页面改变监听器
代码如下 :
- public class MyPageChangeListener implements OnPageChangeListener {
- int one = offset * 2 + bmpw;// 页卡1 -> 页卡2 偏移量
- int two = one * 2;// 页卡1 -> 页卡3 偏移量
- @Override
- public void onPageSelected(int arg0) {
- Animation animation = null;
- switch (arg0) {
- case 0:
- if (currIndex == 1) {
- animation = new TranslateAnimation(one, 0, 0, 0);
- } else if (currIndex == 2) {
- animation = new TranslateAnimation(two, 0, 0, 0);
- }
- break;
- case 1:
- if (currIndex == 0) {
- animation = new TranslateAnimation(offset, one, 0, 0);
- } else if (currIndex == 2) {
- animation = new TranslateAnimation(two, one, 0, 0);
- }
- break;
- case 2:
- if (currIndex == 0) {
- animation = new TranslateAnimation(offset, two, 0, 0);
- } else if (currIndex == 1) {
- animation = new TranslateAnimation(one, two, 0, 0);
- }
- break;
- }
- currIndex = arg0;
- animation.setFillAfter(true);// True:图片停在动画结束位置
- animation.setDuration(300);
- cursor.startAnimation(animation);
- }
public class MyPageChangeListener implements OnPageChangeListener { int one = offset * 2 + bmpw;// 页卡1 -> 页卡2 偏移量 int two = one * 2;// 页卡1 -> 页卡3 偏移量 @Override public void onPageSelected(int arg0) { Animation animation = null; switch (arg0) { case 0: if (currIndex == 1) { animation = new TranslateAnimation(one, 0, 0, 0); } else if (currIndex == 2) { animation = new TranslateAnimation(two, 0, 0, 0); } break; case 1: if (currIndex == 0) { animation = new TranslateAnimation(offset, one, 0, 0); } else if (currIndex == 2) { animation = new TranslateAnimation(two, one, 0, 0); } break; case 2: if (currIndex == 0) { animation = new TranslateAnimation(offset, two, 0, 0); } else if (currIndex == 1) { animation = new TranslateAnimation(one, two, 0, 0); } break; } currIndex = arg0; animation.setFillAfter(true);// True:图片停在动画结束位置 animation.setDuration(300); cursor.startAnimation(animation); }原理是这样,根据滑动到的页面,把游标滑动找指定位置。
这里可能有难度的地方在于,数学……我画了一张图,解释从第一个页面到第二个页面时的距离为什么是“游标宽度+offset*2”,其它距离类似。
这篇就到这了,时间比较紧,而且这个难度不太大,讲的可能不太细。
源码中,给大家列出了一个有Tab交互的Demo,图片如下:
相关文章:
《Android ViewPager多页面滑动切换以及动画效果》
《Android多屏滑动:ViewPager基础使用及PagerTabStrip先天缺陷(附源码)》
源码包含:
1、TestViewPage_scroll_cursor:文中示例源码
2、DWinterTabDemo:带Tab交互的Demo
源码下载地址:http://download.csdn.net/detail/harvic880925/7758941
请大家尊重原创者版权,转载请标明出处:http://blog.csdn.net/harvic880925/article/details/38557517 谢谢
ViewPager 详解(五)-----使用Fragment实现ViewPager滑动 - harvic - 博客频道 - CSDN.NET
前言:前几篇文章讲解了ViewPager的普通实现方法,但android官方最推荐的一种实现方法却是使用fragment,下面我们使用fragment来重新实现一下第一篇《ViewPager 详解(一)---基本入门》所实现的效果。
系列文章:
3、《ViewPager 详解(三)---PagerTabStrip与PagerTitleStrip添加标题栏的异同》
4、《ViewPager 详解(四)----自主实现滑动指示条》
其它相关文章:
5、《Android Fragment完全解析,关于碎片你所需知道的一切》
6、《fragment中嵌套viewpager,vierpager中有多个fragment》
本篇效果图:
在第一个页面加一个Btn 第一页面向第二页面滑动
第二页面向第三个页面滑动
一、概述
从前面几篇文章,我们知道,实现ViewPager是要有适配器的,我们前面用的适配器是PagerAdapter,而对于fragment,它所使用的适配器是:FragmentPagerAdapter.先看看官方对于这个类的解释:(英文下面有中文解释)
原文:
Class Overview
Implementation of
PagerAdapter
that represents each page as aFragment
that is persistently kept in the fragment manager as long as the user can return to the page.This version of the pager is best for use when there are a handful of typically more static fragments to be paged through, such as a set of tabs. The fragment of each page the user visits will be kept in memory, though its view hierarchy may be destroyed when not visible. This can result in using a significant amount of memory since fragment instances can hold on to an arbitrary amount of state. For larger sets of pages, consider
FragmentStatePagerAdapter
.When using FragmentPagerAdapter the host ViewPager must have a valid ID set.
Subclasses only need to implement
getItem(int)
andgetCount()
to have a working adapter.译文:(译的不好,大家可在评论中补充)
FragmentPagerAdapter派生自PagerAdapter,它是用来呈现Fragment页面的,这些Fragment页面会一直保存在fragment manager中,以便用户可以随时取用。
这个适配器最好用于有限个静态fragment页面的管理。尽管不可见的视图有时会被销毁,但用户所有访问过的fragment都会被保存在内存中。因此fragment实例会保存大量的各种状态,这就造成了很大的内存开销。所以如果要处理大量的页面切换,建议使用FragmentStatePagerAdapter.
每一个使用FragmentPagerAdapter的ViewPager都要有一个有效的ID集。(没理解什么意思)
对于FragmentPagerAdapter的派生类,只需要重写getItem(int)和getCount()就可以了。
二、具体实现
1、适配器实现——FragmentPagerAdapter
先看完整代码,再细讲:
- public class FragAdapter extends FragmentPagerAdapter {
- private List<Fragment> mFragments;
- public FragAdapter(FragmentManager fm,List<Fragment> fragments) {
- super(fm);
- // TODO Auto-generated constructor stub
- mFragments=fragments;
- }
- @Override
- public Fragment getItem(int arg0) {
- // TODO Auto-generated method stub
- return mFragments.get(arg0);
- }
- @Override
- public int getCount() {
- // TODO Auto-generated method stub
- return mFragments.size();
- }
- }
public class FragAdapter extends FragmentPagerAdapter { private List<Fragment> mFragments; public FragAdapter(FragmentManager fm,List<Fragment> fragments) { super(fm); // TODO Auto-generated constructor stub mFragments=fragments; } @Override public Fragment getItem(int arg0) { // TODO Auto-generated method stub return mFragments.get(arg0); } @Override public int getCount() { // TODO Auto-generated method stub return mFragments.size(); } }这里有三个函数,根据第一部分的官方文档,可知,对于FragmentPagerAdapter的派生类,只重写getItem(int)和getCount()就可以了。
对于构造函数,这里申请了一个Fragment的List对象,用于保存用于滑动的Fragment对象,并在创造函数中初始化:
- public FragAdapter(FragmentManager fm,List<Fragment> fragments) {
- super(fm);
- // TODO Auto-generated constructor stub
- mFragments=fragments;
- }
public FragAdapter(FragmentManager fm,List<Fragment> fragments) { super(fm); // TODO Auto-generated constructor stub mFragments=fragments; }然后在getItem(int arg0)中,根据传来的参数arg0,来返回当前要显示的fragment,下面是getItem的官方解释,难度不大,不再细讲。
public abstract Fragment getItem (int position)
Return the Fragment associated with a specified position.
最后,getCount()返回用于滑动的fragment总数;
从构造函数所以看出,我们要构造Fragment的集合才行,所以下面我们就先产生我们所需要的Fragment类;2、三个Fragment类
第一个Fragment类:
XML:(layout1.xml)
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:background="#ffffff"
- android:orientation="vertical" >
- <Button android:id="@+id/fragment1_btn"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="show toast"
- />
- </LinearLayout>
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#ffffff" android:orientation="vertical" > <Button android:id="@+id/fragment1_btn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="show toast" /> </LinearLayout>在其中加入了一个Btn
Java代码:
- public class Fragment1 extends Fragment {
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container,
- Bundle savedInstanceState) {
- // TODO Auto-generated method stub
- View view= inflater.inflate(R.layout.layout1, container, false);
- //对View中控件的操作方法
- Button btn = (Button)view.findViewById(R.id.fragment1_btn);
- btn.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- // TODO Auto-generated method stub
- Toast.makeText(getActivity(), "点击了第一个fragment的BTN", Toast.LENGTH_SHORT).show();
- }
- });
- return view;
- }
- }
public class Fragment1 extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // TODO Auto-generated method stub View view= inflater.inflate(R.layout.layout1, container, false); //对View中控件的操作方法 Button btn = (Button)view.findViewById(R.id.fragment1_btn); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Toast.makeText(getActivity(), "点击了第一个fragment的BTN", Toast.LENGTH_SHORT).show(); } }); return view; } }在onCreateView()中返回要显示的View,上面这段代码简单演示了如何对视图里的控件进行操作,难度不大,不再细讲,如果对Fragment不太熟悉的同学,先看看这篇文章:《Android Fragment完全解析,关于碎片你所需知道的一切》
第二个Fragment类:
XML代码:(layout2.xml)原生代码,没有做任何更改
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:background="#ffff00"
- android:orientation="vertical" >
- </LinearLayout>
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#ffff00" android:orientation="vertical" > </LinearLayout>java代码:
- public class Fragment2 extends Fragment {
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container,
- Bundle savedInstanceState) {
- // TODO Auto-generated method stub
- View view=inflater.inflate(R.layout.layout2, container, false);
- return view;
- }
- }
public class Fragment2 extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // TODO Auto-generated method stub View view=inflater.inflate(R.layout.layout2, container, false); return view; } }
第三个Fragment类:XML代码:(layout3.xml)同样,原生代码,没做任何更改
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:background="#ff00ff"
- android:orientation="vertical" >
- </LinearLayout>
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#ff00ff" android:orientation="vertical" > </LinearLayout>java代码:
- public class Fragment3 extends Fragment {
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container,
- Bundle savedInstanceState) {
- // TODO Auto-generated method stub
- View view=inflater.inflate(R.layout.layout3, container, false);
- return view;
- }
- }
public class Fragment3 extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // TODO Auto-generated method stub View view=inflater.inflate(R.layout.layout3, container, false); return view; } }3、主activity实现
核心代码:
- public class MainActivity extends FragmentActivity {
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- //构造适配器
- List<Fragment> fragments=new ArrayList<Fragment>();
- fragments.add(new Fragment1());
- fragments.add(new Fragment2());
- fragments.add(new Fragment3());
- FragAdapter adapter = new FragAdapter(getSupportFragmentManager(), fragments);
- //设定适配器
- ViewPager vp = (ViewPager)findViewById(R.id.viewpager);
- vp.setAdapter(adapter);
- }
- }
public class MainActivity extends FragmentActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //构造适配器 List<Fragment> fragments=new ArrayList<Fragment>(); fragments.add(new Fragment1()); fragments.add(new Fragment2()); fragments.add(new Fragment3()); FragAdapter adapter = new FragAdapter(getSupportFragmentManager(), fragments); //设定适配器 ViewPager vp = (ViewPager)findViewById(R.id.viewpager); vp.setAdapter(adapter); } }首先有一个最值得注意的地方:Activity派生自FragmentActivity,其实这是有关Fragment的基础知识,只有FragmentActivity才能内嵌fragment页面,普通Activity是不行的。
这段代码主要分为两步,第一步:构造适配器;第二步:设定适配器。
先看构造适配器的过程:
- //构造适配器
- List<Fragment> fragments=new ArrayList<Fragment>();
- fragments.add(new Fragment1());
- fragments.add(new Fragment2());
- fragments.add(new Fragment3());
- FragAdapter adapter = new FragAdapter(getSupportFragmentManager(), fragments);
//构造适配器 List<Fragment> fragments=new ArrayList<Fragment>(); fragments.add(new Fragment1()); fragments.add(new Fragment2()); fragments.add(new Fragment3()); FragAdapter adapter = new FragAdapter(getSupportFragmentManager(), fragments);构造一个fragment列表,然后将上面的三个Fragment类对应的实例添加进去,最后生成FragAdapter实例。
至于第二步,设定适配器,没什么好讲的。4、可能出现的问题
问题:在MainActivity中,当写到这句:fragments.add(new Fragment1()); 向Fragment列表中添加Fragement对象实例时,会提示“无法将Fragment1()转换为fragment”
解决办法 :这是因为导入包不一致,一般的问题在于:在Fragment1中导入的是android.app.Fragment, 而在这里导入类确是:android.support.v4.app.Fragment,包不同当然无法转换,统一导入为android.support.v4.app.Fragment之后就正常了.参考文章《android之cannot convert from Fragment1 to Fragment》
源码下载地址:http://download.csdn.net/detail/harvic880925/7777849
请大家尊重原创者版权,转载请标明出处:http://blog.csdn.net/harvic880925/article/details/38660861 不胜感激!