Class Overview:
Layout manager that allows the user to flip left and right through pages of data. You supply an implementation of aPagerAdapterto generate the pages that the view shows.
Note this class is currently under early design and development. The API will likely change in later updates of the compatibility library, requiring changes to the source code of apps when they are compiled against the newer version.
ViewPager is most often used in conjunction with Fragment, which is a convenient way to supply and manage the lifecycle of each page. There are standard adapters implemented for using fragments with the ViewPager, which cover the most common use cases. These are FragmentPagerAdapterandFragmentStatePagerAdapter; each of these classes have simple code showing how to build a full user interface with them.
For more information about how to use ViewPager, read Creating Swipe Views with Tabs.
我来说明一下,viewpager主要是用来创建一个用户可以左右滑动的界面,并且常常用PagerAdapter 来添加显示的数据内容。但是此类是正在开发的类,后面会有改变。并且viewpager常常和Fragment一起来使用,这有得于方便对各个界面的生命周期进行管理,这时我们常常用FragmentPagerAdapter 和 FragmentStatePagerAdapter这二个适配器来给viewpager填充数据。
可以从界面看到,这个viewpager 的Demo,主要包括三个部分。一个是viewpager + fragment的使用样例,第二个是viewpager + tab的使用样例,第三个是使用viewpager来做一个界面指引的例子。
3.2.1 ViewPagerAndFragment.java
package com.example.viewpagerdemo.fragment; import java.util.ArrayList; import java.util.List; import com.example.viewpagerdemo.R; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.view.ViewPager; public class ViewPagerAndFragment extends FragmentActivity { private ViewPager vp = null; private FragAdapter adapter = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.view_pager_and_fragment_main); vp = (ViewPager) findViewById(R.id.viewpager); List<Fragment> fragments = new ArrayList<Fragment>(); fragments.add(new MyFragment1()); fragments.add(new MyFragment2()); fragments.add(new MyFragment3()); adapter = new FragAdapter(getSupportFragmentManager(), fragments); vp.setAdapter(adapter); vp.setCurrentItem(0); } }
package com.example.viewpagerdemo.fragment; import java.util.List; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; public class FragAdapter extends FragmentPagerAdapter{ private List<Fragment> fragments; public FragAdapter(FragmentManager fm) { super(fm); } public FragAdapter(FragmentManager fm, List<Fragment> fragments) { super(fm); this.fragments = fragments; } @Override public Fragment getItem(int position) { return fragments.get(position); } @Override public int getCount() { return fragments.size(); } }
package com.example.viewpagerdemo.fragment; import com.example.viewpagerdemo.R; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; public class MyFragment1 extends Fragment{ private Button bt = null; private TextView tv = null; private int clickCount = 0; @Override public void onActivityCreated(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onActivityCreated(savedInstanceState); } @Override public void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // TODO Auto-generated method stub View view = inflater.inflate(R.layout.my_fragment_1, container, false); tv = (TextView) view.findViewById(R.id.tv); bt = (Button) view.findViewById(R.id.bt); bt.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Toast.makeText(getActivity(), "me is in Fragment 1!!!", Toast.LENGTH_LONG).show(); clickCount++; tv.setText("Fragment 1:"+"you click buttom:"+clickCount); } }); return view; } @Override public void onPause() { // TODO Auto-generated method stub super.onPause(); } }
3.2.4 MyFragment2.java
package com.example.viewpagerdemo.fragment; import com.example.viewpagerdemo.R; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; public class MyFragment2 extends Fragment{ private Button bt = null; private TextView tv = null; private int clickCount = 0; @Override public void onActivityCreated(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onActivityCreated(savedInstanceState); } @Override public void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // TODO Auto-generated method stub View view = inflater.inflate(R.layout.my_fragment_2, container, false); tv = (TextView) view.findViewById(R.id.tv); bt = (Button) view.findViewById(R.id.bt); bt.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Toast.makeText(getActivity(), "me is in Fragment 2!!!", Toast.LENGTH_LONG).show(); clickCount++; tv.setText("Fragment 2:"+"you click buttom:"+clickCount); } }); return view; } @Override public void onPause() { // TODO Auto-generated method stub super.onPause(); } }
3.2.5 MyFragment3.java
package com.example.viewpagerdemo.fragment; import com.example.viewpagerdemo.R; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; public class MyFragment3 extends Fragment{ private Button bt = null; private TextView tv = null; private int clickCount = 0; @Override public void onActivityCreated(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onActivityCreated(savedInstanceState); } @Override public void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // TODO Auto-generated method stub View view = inflater.inflate(R.layout.my_fragment_3, container, false); tv = (TextView) view.findViewById(R.id.tv); bt = (Button) view.findViewById(R.id.bt); bt.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Toast.makeText(getActivity(), "me is in Fragment 3!!!", Toast.LENGTH_LONG).show(); clickCount++; tv.setText("Fragment 3:"+"you click buttom:"+clickCount); } }); return view; } @Override public void onPause() { // TODO Auto-generated method stub super.onPause(); } }
3.2.6 view_pager_and_fragment_main.xml
<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" > <android.support.v4.view.ViewPager android:id="@+id/viewpager" android:layout_width="wrap_content" android:layout_height="wrap_content" android:flipInterval="30" android:persistentDrawingCache="animation" /> </RelativeLayout>
4.2.1 ViewPagerAndTab.java
package com.example.viewpagerdemo.tab; import java.util.ArrayList; import java.util.List; import com.example.viewpagerdemo.R; import android.app.Activity; import android.graphics.BitmapFactory; import android.graphics.Color; import android.graphics.Matrix; import android.os.Bundle; import android.support.v4.view.ViewPager; import android.support.v4.view.ViewPager.OnPageChangeListener; import android.util.DisplayMetrics; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.animation.Animation; import android.view.animation.TranslateAnimation; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; public class ViewPagerAndTab extends Activity { private String TAG = "ViewPagerAndTab"; private ViewPager viewPager; private ImageView imageView; private TextView textView1,textView2,textView3; private int offset = 0; private int currIndex = 0; private int bmpW; private List<View> views; private View view1,view2,view3; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.view_pager_and_tab_main); InitImageView(); InitTextView(); InitViewPager(); } private void InitImageView() { // TODO Auto-generated method stub imageView= (ImageView) findViewById(R.id.cursor); bmpW = BitmapFactory.decodeResource(getResources(), R.drawable.cursor).getWidth(); Log.i(TAG, "bmpW:"+bmpW); DisplayMetrics dm = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(dm); int screenW = dm.widthPixels; Log.i(TAG, "screenW:"+screenW); offset = (screenW / 3 - bmpW) / 2; Log.i(TAG, "offset:"+offset); Matrix matrix = new Matrix(); matrix.postTranslate(offset, 0); imageView.setImageMatrix(matrix); } private void InitTextView() { // TODO Auto-generated method stub textView1 = (TextView) findViewById(R.id.text1); textView1.setTextColor(Color.GREEN); textView2 = (TextView) findViewById(R.id.text2); textView3 = (TextView) findViewById(R.id.text3); textView1.setOnClickListener(new MyOnClickListener(0)); textView2.setOnClickListener(new MyOnClickListener(1)); textView3.setOnClickListener(new MyOnClickListener(2)); } private void InitViewPager() { // TODO Auto-generated method stub viewPager=(ViewPager) findViewById(R.id.viewpager); views=new ArrayList<View>(); LayoutInflater inflater=getLayoutInflater(); view1=inflater.inflate(R.layout.layout_tab_1, null); view2=inflater.inflate(R.layout.layout_tab_2, null); view3=inflater.inflate(R.layout.layout_tab_3, null); views.add(view1); views.add(view2); views.add(view3); viewPager.setAdapter(new MyPagerAdapter(views)); viewPager.setCurrentItem(0); viewPager.setOnPageChangeListener(new MyOnPageChangeListener()); } private class MyOnClickListener implements OnClickListener{ private int index=0; public MyOnClickListener(int i){ index=i; } public void onClick(View v) { viewPager.setCurrentItem(index); } } public class MyOnPageChangeListener implements OnPageChangeListener{ int one = offset * 2 + bmpW; int two = one * 2; public MyOnPageChangeListener(){ Log.i(TAG, "one:"+one); Log.i(TAG, "two:"+two); } public void onPageScrollStateChanged(int arg0) { } public void onPageScrolled(int arg0, float arg1, int arg2) { } 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; } */ Animation animation = new TranslateAnimation(one*currIndex, one*arg0, 0, 0); currIndex = arg0; animation.setFillAfter(true);// True:图片停在动画结束位置 animation.setDuration(300); imageView.startAnimation(animation); Toast.makeText(ViewPagerAndTab.this, "you selec:"+ viewPager.getCurrentItem()+"tab", Toast.LENGTH_SHORT).show(); switch (arg0) { case 0: textView1.setTextColor(Color.GREEN); textView2.setTextColor(Color.BLACK); textView3.setTextColor(Color.BLACK); break; case 1: textView2.setTextColor(Color.GREEN); textView1.setTextColor(Color.BLACK); textView3.setTextColor(Color.BLACK); break; case 2: textView3.setTextColor(Color.GREEN); textView1.setTextColor(Color.BLACK); textView2.setTextColor(Color.BLACK); break; default: break; } } } }
4.2.2 MyPagerAdapter.java
package com.example.viewpagerdemo.tab; import java.util.List; import android.support.v4.view.PagerAdapter; import android.view.View; import android.view.ViewGroup; public class MyPagerAdapter extends PagerAdapter{ private List<View> viewList; public MyPagerAdapter(List<View> viewList){ this.viewList = viewList; } @Override public boolean isViewFromObject(View arg0, Object arg1) { return arg0 == arg1; } @Override public int getCount() { return viewList.size(); } @Override public void destroyItem(ViewGroup container, int position,Object object) { container.removeView(viewList.get(position)); } @Override public int getItemPosition(Object object) { return super.getItemPosition(object); } @Override public Object instantiateItem(ViewGroup container, int position) { container.addView(viewList.get(position),0); return viewList.get(position); } }
4.2.3 view_pager_and_tab_main.xml
<RelativeLayout 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" > <LinearLayout android:id="@+id/linearLayout1" android:layout_width="fill_parent" android:layout_height="60.0dip" android:background="#FFFFFF" > <TextView android:id="@+id/text1" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_weight="1.0" android:gravity="center" android:text=" @me" android:textColor="#000000" android:textSize="20.0dip" /> <TextView android:id="@+id/text2" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_weight="1.0" android:gravity="center" android:text="comment:" android:textColor="#000000" android:textSize="20.0dip" /> <TextView android:id="@+id/text3" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_weight="1.0" android:gravity="center" android:text="private message" android:textColor="#000000" android:textSize="20.0dip" /> </LinearLayout> <ImageView android:id="@+id/cursor" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_below="@id/linearLayout1" android:scaleType="matrix" android:src="@drawable/cursor" /> <android.support.v4.view.ViewPager android:id="@+id/viewpager" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/cursor" android:layout_gravity="center" android:layout_weight="1.0" android:background="#00ffed" android:flipInterval="30" android:persistentDrawingCache="animation" /> </RelativeLayout>
5.2.1 ViewPagerAndImageGuide.java
package com.example.viewpagerdemo.image.guide; import com.example.viewpagerdemo.R; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.os.Handler; import android.os.Message; public class ViewPagerAndImageGuide extends Activity { private boolean isFirstIn = false; private static final int GO_HOME = 1000; private static final int GO_GUIDE = 1001; private static final long SPLASH_DELAY_MILLIS = 500; private static final String SHAREDPREFERENCES_NAME = "first_pref"; private Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case GO_HOME: //goHome(); goGuide(); break; case GO_GUIDE: goGuide(); break; } super.handleMessage(msg); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); init(); } private void init() { SharedPreferences preferences = getSharedPreferences(SHAREDPREFERENCES_NAME, MODE_PRIVATE); isFirstIn = preferences.getBoolean("isFirstIn", true); if (!isFirstIn) { mHandler.sendEmptyMessageDelayed(GO_HOME, SPLASH_DELAY_MILLIS); } else { mHandler.sendEmptyMessageDelayed(GO_GUIDE, SPLASH_DELAY_MILLIS); } } private void goHome() { // Intent intent = new Intent(ViewPagerAndImageGuide.this, HomeActivity.class); // startActivity(intent); // finish(); } private void goGuide() { Intent intent = new Intent(this, GuideActivity.class); startActivity(intent); finish(); } }
5.2.2 GuideActivity.java
package com.example.viewpagerdemo.image.guide; import java.util.ArrayList; import java.util.List; import com.example.viewpagerdemo.R; import android.app.Activity; import android.os.Bundle; import android.support.v4.view.ViewPager; import android.support.v4.view.ViewPager.OnPageChangeListener; import android.view.LayoutInflater; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; public class GuideActivity extends Activity implements OnPageChangeListener{ private ViewPager viewpager; private ViewPagerAdapter vpAdapter; private List<View> views; private LinearLayout ll; private int currentIndex; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.guide_main); initViews(); initDots(); } private void initViews() { // TODO Auto-generated method stub LayoutInflater inflater = LayoutInflater.from(this); views = new ArrayList<View>(); views.add(inflater.inflate(R.layout.guide_one, null)); views.add(inflater.inflate(R.layout.guide_two, null)); views.add(inflater.inflate(R.layout.guide_three, null)); views.add(inflater.inflate(R.layout.guide_four, null)); vpAdapter = new ViewPagerAdapter(views, this); viewpager = (ViewPager) findViewById(R.id.viewpager); viewpager.setAdapter(vpAdapter); viewpager.setOnPageChangeListener(this); } private void initDots() { // TODO Auto-generated method stub ll = (LinearLayout) findViewById(R.id.ll); for (int i = 0; i < views.size(); i++) { ImageView dotImage = new ImageView(this); if(i == 0){ dotImage.setBackgroundDrawable(getResources().getDrawable(R.drawable.green)); }else{ dotImage.setBackgroundDrawable(getResources().getDrawable(R.drawable.black)); } ll.addView(dotImage); } } private void setCurrentDot(int position) { if (position < 0 || position > views.size() - 1 || currentIndex == position) { return; } ll.removeAllViews(); for (int i = 0; i < views.size(); i++) { ImageView dotImage = new ImageView(this); if(i == position){ dotImage.setBackgroundDrawable(getResources().getDrawable(R.drawable.green)); }else{ dotImage.setBackgroundDrawable(getResources().getDrawable(R.drawable.black)); } ll.addView(dotImage); } currentIndex = position; } @Override public void onPageScrollStateChanged(int arg0) { // TODO Auto-generated method stub } @Override public void onPageScrolled(int arg0, float arg1, int arg2) { // TODO Auto-generated method stub } @Override public void onPageSelected(int arg0) { // TODO Auto-generated method stub setCurrentDot(arg0); } }
5.2.3 ViewPagerAdapter.java
package com.example.viewpagerdemo.image.guide; import java.util.List; import com.example.viewpagerdemo.R; import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.support.v4.view.PagerAdapter; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.Button; import android.widget.Toast; public class ViewPagerAdapter extends PagerAdapter { private List<View> views; private Activity activity; private static final String SHAREDPREFERENCES_NAME = "first_pref"; public ViewPagerAdapter(List<View> views, Activity activity) { this.views = views; this.activity = activity; } @Override public void destroyItem(ViewGroup container, int position, Object object) { // TODO Auto-generated method stub container.removeView(views.get(position)); } @Override public void finishUpdate(View arg0) { } @Override public int getCount() { if (views != null) { return views.size(); } return 0; } @Override public Object instantiateItem(ViewGroup container, int position) { // TODO Auto-generated method stub container.addView(views.get(position), 0); if (position == views.size() - 1) { Button mStartImageButton = (Button)container.findViewById(R.id.iv_start); mStartImageButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { setGuided(); goHome(); Toast.makeText(activity, "click button", Toast.LENGTH_SHORT).show(); } }); } return views.get(position); } private void goHome() { // Intent intent = new Intent(activity, MainActivity.class); // activity.startActivity(intent); // activity.finish(); } private void setGuided() { SharedPreferences preferences = activity.getSharedPreferences( SHAREDPREFERENCES_NAME, Context.MODE_PRIVATE); Editor editor = preferences.edit(); editor.putBoolean("isFirstIn", false); editor.commit(); } @Override public boolean isViewFromObject(View arg0, Object arg1) { return (arg0 == arg1); } }
5.2.4 guide_main.xml
<RelativeLayout 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.support.v4.view.ViewPager android:id="@+id/viewpager" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <LinearLayout android:id="@+id/ll" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:gravity="center" android:orientation="horizontal" > </LinearLayout> </RelativeLayout>
http://download.csdn.net/detail/hfreeman2008/7810731
(1)Android ViewPager使用详解
http://blog.csdn.net/wangjinyu501/article/details/8169924/
(2)viewpager 官方文档说明
http://developer.android.com/reference/android/support/v4/view/ViewPager.html
(3)viewpager 官方的几个使用样例
http://developer.android.com/training/implementing-navigation/lateral.html