首先感谢以下文章的作者!这里只是本人学习过程中觉得受教的贴,做个整合,以便日后查看。如有冒犯,请通知本人,本人即刻删除。
官方参考文档:http://www.android-doc.com/reference/android/support/v4/view/PagerAdapter.html
文章出处:http://blog.csdn.net/wangjinyu501/article/details/8169924/
这是谷歌官方给我们提供的一个兼容低版本安卓设备的软件包,里面包囊了只有在安卓3.0以上可以使用的api。而viewpager就是其中之一利用它,我们可以做很多事情,从最简单的导航,到页面菜单等等。那如何使用它呢,与LisstView类似,我们也需要一个适配器,他就是PagerAdapter。看一下api的图片,
ViewPager的功能就是可以使视图滑动,就像Lanucher左右滑动那样。分三个步骤来使用它:
1.在住布局文件里加入
- <android.support.v4.view.ViewPager 这个组件,注意这个组件是用来显示左右滑动的界面的,如果不加载xml布局文件,他是不会显示内容的。
- android:id="@+id/viewpager"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_gravity="center" >
2.加载要显示的页卡,
- LayoutInflater lf = getLayoutInflater().from(this);
- view1 = lf.inflate(R.layout.layout1, null);
- view2 = lf.inflate(R.layout.layout2, null);
- view3 = lf.inflate(R.layout.layout3, null);
-
- viewList = new ArrayList<View>();
- viewList.add(view1);
- viewList.add(view2);
- viewList.add(view3);
3.在Activity里实例化ViewPager组件,并设置它的Adapter(就是PagerAdapter,方法与ListView一样的),在这里一般需要重写PagerAdapter。
- PagerAdapter pagerAdapter = new PagerAdapter() {
-
- @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 CharSequence getPageTitle(int position) {
-
- return titleList.get(position);
- }
-
- @Override
- public Object instantiateItem(ViewGroup container, int position) {
- container.addView(viewList.get(position));
- weibo_button=(Button) findViewById(R.id.button1);
- weibo_button.setOnClickListener(new OnClickListener() {
-
- public void onClick(View v) {
- intent=new Intent(ViewPagerDemo.this,WeiBoActivity.class);
- startActivity(intent);
- }
- });
- return viewList.get(position);
- }
-
- };
- viewPager.setAdapter(pagerAdapter);
这是重写PagerAdapter的一个方法,我们还可以这样做:
- public class MyViewPagerAdapter extends PagerAdapter{
- private List<View> mListViews;
-
- public MyViewPagerAdapter(List<View> mListViews) {
- this.mListViews = mListViews;
- }
-
- @Override
- public void destroyItem(ViewGroup container, int position, Object object) {
- container.removeView(mListViews.get(position));
- }
-
-
- @Override
- public Object instantiateItem(ViewGroup container, int position) {
- container.addView(mListViews.get(position), 0);
- return mListViews.get(position);
- }
-
- @Override
- public int getCount() {
- return mListViews.size();
- }
-
- @Override
- public boolean isViewFromObject(View arg0, Object arg1) {
- return arg0==arg1;
- }
- }
大同小异,有一定很重要,就是我们需要重写哪些方法。从上面的图片可以看到,ViewPager的适配器是PagerAdapter,它是基类提供适配器来填充页面ViewPager内部,你很可能想要使用一个更具体的实现,如FragmentPagerAdapter或FragmentStatePagerAdapter。在这里需要说明一下,其实ViewPager应该和Fragment一起使用,至少谷歌官方是这么想的,但是在3.0之下,我们没有必要这么做。下面要注意,当你实现一个PagerAdapter,你必须至少覆盖以下方法:
instantiateItem(ViewGroup, int)
destroyItem(ViewGroup, int, Object)
getCount()
isViewFromObject(View, Object)
从上面的例子中可以看到,我们最少也是实现了上面四个方法,当然如果你想让程序更健壮或是功能更全面,你可以重写其他的方法。下面看一下第一个完整的示例代码:
主页面Activity:
- package com.example.viewpagerdemo;
-
- import java.util.ArrayList;
- import java.util.List;
- import android.os.Bundle;
- import android.app.Activity;
- import android.content.Context;
- import android.content.Intent;
- import android.support.v4.view.PagerAdapter;
- import android.support.v4.view.PagerTabStrip;
- import android.support.v4.view.PagerTitleStrip;
- import android.support.v4.view.ViewPager;
- import android.util.AttributeSet;
- import android.view.LayoutInflater;
- import android.view.Menu;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.view.ViewGroup;
- import android.widget.Button;
-
- public class ViewPagerDemo extends Activity {
-
- private View view1, view2, view3;
- private ViewPager viewPager;
- private PagerTitleStrip pagerTitleStrip;
- private PagerTabStrip pagerTabStrip;
- private List<View> viewList;
- private List<String> titleList;
- private Button weibo_button;
- private Intent intent;
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_view_pager_demo);
- initView();
- }
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- view1 = findViewById(R.layout.layout1);
- view2 = findViewById(R.layout.layout2);
- view3 = findViewById(R.layout.layout3);
-
- LayoutInflater lf = getLayoutInflater().from(this);
- view1 = lf.inflate(R.layout.layout1, null);
- view2 = lf.inflate(R.layout.layout2, null);
- view3 = lf.inflate(R.layout.layout3, null);
-
- viewList = new ArrayList<View>();
- viewList.add(view1);
- viewList.add(view2);
- viewList.add(view3);
-
- titleList = new ArrayList<String>();
- titleList.add("wp");
- titleList.add("jy");
- titleList.add("jh");
-
- PagerAdapter pagerAdapter = new PagerAdapter() {
-
- @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 CharSequence getPageTitle(int position) {
-
- return titleList.get(position);
-
- }
-
- @Override
- public Object instantiateItem(ViewGroup container, int position) {
- container.addView(viewList.get(position));
- weibo_button=(Button) findViewById(R.id.button1);
- weibo_button.setOnClickListener(new OnClickListener() {
-
- public void onClick(View v) {
- intent=new Intent(ViewPagerDemo.this,WeiBoActivity.class);
- startActivity(intent);
- }
- });
- return viewList.get(position);
- }
-
- };
- viewPager.setAdapter(pagerAdapter);
- }
-
- @Override
- public boolean onCreateOptionsMenu(Menu menu) {
- getMenuInflater().inflate(R.menu.activity_view_pager_demo, menu);
- return true;
- }
-
- }
它的布局文件:
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:orientation="vertical" >
-
- <android.support.v4.view.ViewPager
- android:id="@+id/viewpager"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_gravity="center" >
-
- <android.support.v4.view.PagerTabStrip
- android:id="@+id/pagertab"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_gravity="top"/>
-
- </android.support.v4.view.ViewPager>
-
- </LinearLayout>
- <!--注意事项:
- 1.这里ViewPager和 PagerTabStrip都要把包名写全了,不然会ClassNotFount
- 2.API中说:在布局xml把PagerTabStrip当做ViewPager的一个子标签来用,不能拿出来,不然还是会报错
- 3.在PagerTabStrip标签中可以用属性android:layout_gravity=TOP|BOTTOM来指定title的位置
- 4.如果要显示出PagerTabStrip某一页的title,需要在ViewPager的adapter中实现getPageTitle(int)-->
这样就完成了一个简单的ViewPager的使用示例,看一下效果图:
可以左右滑动页卡,但是仔细看一下,标题的效果不好,不能一次显示一个,而且标题还滑动。其实在api里面提供了一个
pagerTabStrip.setTextSpacing()来设置标题的距离,但是我在这里设置了,没有效果不知道为什么,明白的朋友希望能够赐教一下。
所以就有人使用下面这样的方法来仿微博的效果,,
这个标题就固定了,而且可以左右滑动,也有下面的横线,来指示页卡。方法和上面的差不多,区别在于这个横线需要我们自己来做,其实就是一个图片。这个例子是网上的一篇文章,看代码:
主Activity:
- package com.example.viewpagerdemo;
-
- import java.util.ArrayList;
- import java.util.List;
- import android.app.Activity;
- import android.graphics.BitmapFactory;
- import android.graphics.Matrix;
- import android.os.Bundle;
- import android.support.v4.view.PagerAdapter;
- import android.support.v4.view.ViewPager;
- import android.support.v4.view.ViewPager.OnPageChangeListener;
- import android.util.DisplayMetrics;
- 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.view.ViewGroup;
- import android.widget.ImageView;
- import android.widget.TextView;
- import android.widget.Toast;
-
- public class WeiBoActivity extends Activity {
-
- private ViewPager viewPager;
- private ImageView imageView;
- private TextView textView1,textView2,textView3;
- private List<View> views;
- private int offset = 0;
- private int currIndex = 0;
- private int bmpW;
- private View view1,view2,view3;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.weibo);
- InitImageView();
- InitTextView();
- InitViewPager();
- }
-
- private void InitViewPager() {
- viewPager=(ViewPager) findViewById(R.id.vPager);
- views=new ArrayList<View>();
- LayoutInflater inflater=getLayoutInflater();
- view1=inflater.inflate(R.layout.lay1, null);
- view2=inflater.inflate(R.layout.lay2, null);
- view3=inflater.inflate(R.layout.lay3, null);
- views.add(view1);
- views.add(view2);
- views.add(view3);
- viewPager.setAdapter(new MyViewPagerAdapter(views));
- viewPager.setCurrentItem(0);
- viewPager.setOnPageChangeListener(new MyOnPageChangeListener());
- }
-
-
-
-
- private void InitTextView() {
- textView1 = (TextView) findViewById(R.id.text1);
- 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 InitImageView() {
- imageView= (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 / 3 - bmpW) / 2;
- Matrix matrix = new Matrix();
- matrix.postTranslate(offset, 0);
- imageView.setImageMatrix(matrix);
- }
- <img src="http://img.my.csdn.net/uploads/201211/10/1352554452_1685.jpg" alt="">
-
-
-
- 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 MyViewPagerAdapter extends PagerAdapter{
- private List<View> mListViews;
-
- public MyViewPagerAdapter(List<View> mListViews) {
- this.mListViews = mListViews;
- }
-
- @Override
- public void destroyItem(ViewGroup container, int position, Object object) {
- container.removeView(mListViews.get(position));
- }
-
-
- @Override
- public Object instantiateItem(ViewGroup container, int position) {
- container.addView(mListViews.get(position), 0);
- return mListViews.get(position);
- }
-
- @Override
- public int getCount() {
- return mListViews.size();
- }
-
- @Override
- public boolean isViewFromObject(View arg0, Object arg1) {
- return arg0==arg1;
- }
- }
-
- public class MyOnPageChangeListener implements OnPageChangeListener{
-
- int one = offset * 2 + bmpW;
- int two = one * 2;
- public void onPageScrollStateChanged(int arg0) {
-
-
- }
-
- public void onPageScrolled(int arg0, float arg1, int arg2) {
-
-
- }
-
- public void onPageSelected(int arg0) {
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- Animation animation = new TranslateAnimation(one*currIndex, one*arg0, 0, 0);
- currIndex = arg0;
- animation.setFillAfter(true);
- animation.setDuration(300);
- imageView.startAnimation(animation);
- Toast.makeText(WeiBoActivity.this, "您选择了"+ viewPager.getCurrentItem()+"页卡", Toast.LENGTH_SHORT).show();
- }
-
- }
- }
它的布局文件:
- <?xml version="1.0" encoding="utf-8"?>
- lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:orientation="vertical" >
-
- <LinearLayout
- android:id="@+id/linearLayout1"
- android:layout_width="fill_parent"
- android:layout_height="40.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=" @我"
- 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="评论"
- 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="私信"
- android:textColor="#000000"
- android:textSize="20.0dip" />
- </LinearLayout>
-
- <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/vPager"
- android:layout_width="wrap_content"
- android:layout_height="0dp"
- android:layout_gravity="center"
- android:layout_weight="1.0"
- android:background="#000000"
- android:flipInterval="30"
- android:persistentDrawingCache="animation" />
- lt;/LinearLayout>
效果如下:
下面使用ViewPager来实现一个程序引导的demo:
一般来说,引导界面是出现第一次运行时出现的,之后不会再出现。所以需要记录是否是第一次使用程序,办法有很多,最容易想到的就是使用SharedPreferences来保存。步骤如下:
1、程序进入欢迎界面,SplashActivity,在这里读取SharedPreferences里面的变量,先设置为true。进入引导界面,然后设置为false。
2、之后每次进入欢迎界面读取SharedPreferences里面的变量,因为是false,所以不会运行引导界面了。
代码如下:
SplashActivity.java,欢迎界面。
- 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 SplashActivity extends Activity {
- boolean isFirstIn = false;
-
- private static final int GO_HOME = 1000;
- private static final int GO_GUIDE = 1001;
-
- private static final long SPLASH_DELAY_MILLIS = 3000;
-
- 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();
- break;
- case GO_GUIDE:
- goGuide();
- break;
- }
- super.handleMessage(msg);
- }
- };
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.splash);
-
- 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(SplashActivity.this, MainActivity.class);
- SplashActivity.this.startActivity(intent);
- SplashActivity.this.finish();
- }
-
- private void goGuide() {
- Intent intent = new Intent(SplashActivity.this, GuideActivity.class);
- SplashActivity.this.startActivity(intent);
- SplashActivity.this.finish();
- }
- }
GuideActivity.java引导界面:
ViewPagerAdapter.java。ViewPager的适配器:
- import java.util.List;
- import android.app.Activity;
- import android.content.Context;
- import android.content.Intent;
- import android.content.SharedPreferences;
- import android.content.SharedPreferences.Editor;
- import android.os.Parcelable;
- import android.support.v4.view.PagerAdapter;
- import android.support.v4.view.ViewPager;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.ImageView;
- import cn.eoe.leigo.splash.MainActivity;
- import cn.eoe.leigo.splash.R;
-
-
-
- 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(View arg0, int arg1, Object arg2) {
- ((ViewPager) arg0).removeView(views.get(arg1));
- }
-
- @Override
- public void finishUpdate(View arg0) {
- }
-
-
- @Override
- public int getCount() {
- if (views != null) {
- return views.size();
- }
- return 0;
- }
-
-
- @Override
- public Object instantiateItem(View arg0, int arg1) {
- ((ViewPager) arg0).addView(views.get(arg1), 0);
- if (arg1 == views.size() - 1) {
- ImageView mStartWeiboImageButton = (ImageView) arg0
- .findViewById(R.id.iv_start_weibo);
- mStartWeiboImageButton.setOnClickListener(new OnClickListener() {
-
- @Override
- public void onClick(View v) {
-
- setGuided();
- goHome();
-
- }
-
- });
- }
- return views.get(arg1);
- }
-
- 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);
- }
-
- @Override
- public void restoreState(Parcelable arg0, ClassLoader arg1) {
- }
-
- @Override
- public Parcelable saveState() {
- return null;
- }
-
- @Override
- public void startUpdate(View arg0) {
- }
-
- }
至于MainActivity随便了。
效果如下:
http://www.fjzzled.com/hzjdyyyyjs/95.html
http://www.fjzzled.com/hzjdyyyyjs/94.html
http://www.sjys365.com/smzl/2999.html
http://www.sjys365.com/smzl/2998.html
所以总结一下,我们可以使用ViewPager做什么:
1.程序使用导航,外加底部圆点的效果,这个在微信示例里介绍了
2.页卡滑动,加上菜单的效果,不管是之前的支持手势也支持底部图标点击的微信,还是今天的微博。
==============================================================================================================
文章出处:http://blog.csdn.net/xipiaoyouzi/article/details/12121131
android ViewPager滑动事件讲解
今天在做项目的时候,由于要处理viewPager页面滑动的事件,所以对其进行了一个小小的研究:
首先ViewPager在处理滑动事件的时候要用到OnPageChangeListener
OnPageChangeListener这个接口需要实现三个方法:(onPageScrollStateChanged,onPageScrolled ,onPageSelected)
onPageScrollStateChanged(int arg0) ,此方法是在状态改变的时候调用,其中arg0这个参数
有三种状态(0,1,2)。arg0 ==1的时辰默示正在滑动,arg0==2的时辰默示滑动完毕了,arg0==0的时辰默示什么都没做。
当页面开始滑动的时候,三种状态的变化顺序为(1,2,0),演示如下:
当viewPager状态改变时候的代码块:
打印结果:
onPageScrolled(int arg0,float arg1,int arg2) ,当页面在滑动的时候会调用此方法,在滑动被停止之前,此方法回一直得到
调用。其中三个参数的含义分别为:
arg0 :当前页面,及你点击滑动的页面
arg1:当前页面偏移的百分比
arg2:当前页面偏移的像素位置
(参见官网:http://docs.eoeandroid.com/reference/android/support/v4/view/ViewPager.OnPageChangeListener.html#onPageScrolled(int, float, int))
演示如下:
页面滚动时侯代码:
日志打印:
onPageSelected(int arg0) : 此方法是页面跳转完后得到调用,arg0是你当前选中的页面的Position(位置编号)。
=======================================================================================================================
文章出处:http://www.cnblogs.com/dwinter/archive/2012/02/27/AndroidViewPager%E5%A4%9A%E9%A1%B5%E9%9D%A2%E6%BB%91%E5%8A%A8%E5%88%87%E6%8D%A2%E4%BB%A5%E5%8F%8A%E5%8A%A8%E7%94%BB%E6%95%88%E6%9E%9C.html
一、首先,我们来看一下效果图,这是新浪微博的Tab滑动效果。我们可以手势滑动,也可以点击上面的头标进行切换。与此同方式,
白色横条会移动到相应的页卡头标下。这是一个动画效果,白条是缓慢滑动过去的。好了,接下来我们就来实现它。
二、在开始前,我们先要认识一个控件,ViewPager。它是google SDk中自带的一个附加包的一个类,可以用来实现屏幕间的切换。
这个附加包是android-support-v4.jar,在最后的源码中会提供给大家,在libs文件夹中。当然你也可以自己从网上搜索最新的版本。
找到它后,我们需要在项目中添加
三、我们先做界面,
界面设计很简单,第一行三个头标,第二行动画图片,第三行页卡内容展示。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:umadsdk="http://schemas.android.com/apk/res/com.LoveBus"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<LinearLayout
android:id="@+id/linearLayout1"
android:layout_width="fill_parent"
android:layout_height="100.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="页卡1"
android:textColor="#000000"
android:textSize="22.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="页卡2"
android:textColor="#000000"
android:textSize="22.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="页卡3"
android:textColor="#000000"
android:textSize="22.0dip" />
</LinearLayout>
<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/vPager"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1.0"
android:background="#000000"
android:flipInterval="30"
android:persistentDrawingCache="animation" />
</LinearLayout>
我们要展示三个页卡,所以还需要三个页卡内容的界面设计,这里我们只设置了背景颜色,能起到区别作用即可。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:background="#158684" >
</LinearLayout>
四、代码部分要进行初始化的工作
(1) 先来变量的定义
private ViewPager mPager;//页卡内容
private List<View> listViews; // Tab页面列表
private ImageView cursor;// 动画图片
private TextView t1, t2, t3;// 页卡头标
private int offset = 0;// 动画图片偏移量
private int currIndex = 0;// 当前页卡编号
private int bmpW;// 动画图片宽度
(2) 初始化头标
1 /**
2 * 初始化头标
3 */
4 private void InitTextView() {
5 t1 = (TextView) findViewById(R.id.text1);
6 t2 = (TextView) findViewById(R.id.text2);
7 t3 = (TextView) findViewById(R.id.text3);
8
9 t1.setOnClickListener(new MyOnClickListener(0));
10 t2.setOnClickListener(new MyOnClickListener(1));
11 t3.setOnClickListener(new MyOnClickListener(2));
12 }
1 /**
2 * 头标点击监听
3 */
4 public class MyOnClickListener implements View.OnClickListener {
5 private int index = 0;
6
7 public MyOnClickListener(int i) {
8 index = i;
9 }
10
11 @Override
12 public void onClick(View v) {
13 mPager.setCurrentItem(index);
14 }
15 };
相信大家看后都没什么问题,点击第几个,就展示第几个页卡内容。
(3) 初始化页卡内容区
1 /**
2 * 初始化ViewPager
3 */
4 private void InitViewPager() {
5 mPager = (ViewPager) findViewById(R.id.vPager);
6 listViews = new ArrayList<View>();
7 LayoutInflater mInflater = getLayoutInflater();
8 listViews.add(mInflater.inflate(R.layout.lay1, null));
9 listViews.add(mInflater.inflate(R.layout.lay2, null));
10 listViews.add(mInflater.inflate(R.layout.lay3, null));
11 mPager.setAdapter(new MyPagerAdapter(listViews));
12 mPager.setCurrentItem(0);
13 mPager.setOnPageChangeListener(new MyOnPageChangeListener());
14 }
我们将三个页卡界面装入其中,默认显示第一个页卡。这里我们还需要实现一个适配器。
1 /**
2 * ViewPager适配器
3 */
4 public class MyPagerAdapter extends PagerAdapter {
5 public List<View> mListViews;
6
7 public MyPagerAdapter(List<View> mListViews) {
8 this.mListViews = mListViews;
9 }
10
11 @Override
12 public void destroyItem(View arg0, int arg1, Object arg2) {
13 ((ViewPager) arg0).removeView(mListViews.get(arg1));
14 }
15
16 @Override
17 public void finishUpdate(View arg0) {
18 }
19
20 @Override
21 public int getCount() {
22 return mListViews.size();
23 }
24
25 @Override
26 public Object instantiateItem(View arg0, int arg1) {
27 ((ViewPager) arg0).addView(mListViews.get(arg1), 0);
28 return mListViews.get(arg1);
29 }
30
31 @Override
32 public boolean isViewFromObject(View arg0, Object arg1) {
33 return arg0 == (arg1);
34 }
35
36 @Override
37 public void restoreState(Parcelable arg0, ClassLoader arg1) {
38 }
39
40 @Override
41 public Parcelable saveState() {
42 return null;
43 }
44
45 @Override
46 public void startUpdate(View arg0) {
47 }
48 }
这里我们实现了各页卡的装入和卸载
(3) 初始化动画
1 /**
2 * 初始化动画
3 */
4 private void InitImageView() {
5 cursor = (ImageView) findViewById(R.id.cursor);
6 bmpW = BitmapFactory.decodeResource(getResources(), R.drawable.a)
7 .getWidth();// 获取图片宽度
8 DisplayMetrics dm = new DisplayMetrics();
9 getWindowManager().getDefaultDisplay().getMetrics(dm);
10 int screenW = dm.widthPixels;// 获取分辨率宽度
11 offset = (screenW / 3 - bmpW) / 2;// 计算偏移量
12 Matrix matrix = new Matrix();
13 matrix.postTranslate(offset, 0);
14 cursor.setImageMatrix(matrix);// 设置动画初始位置
15 }
根据屏幕的分辨率和图片的宽度计算动画移动的偏移量
实现页卡切换监听
1 /**
2 * 页卡切换监听
3 */
4 public class MyOnPageChangeListener implements OnPageChangeListener {
5
6 int one = offset * 2 + bmpW;// 页卡1 -> 页卡2 偏移量
7 int two = one * 2;// 页卡1 -> 页卡3 偏移量
8
9 @Override
10 public void onPageSelected(int arg0) {
11 Animation animation = null;
12 switch (arg0) {
13 case 0:
14 if (currIndex == 1) {
15 animation = new TranslateAnimation(one, 0, 0, 0);
16 } else if (currIndex == 2) {
17 animation = new TranslateAnimation(two, 0, 0, 0);
18 }
19 break;
20 case 1:
21 if (currIndex == 0) {
22 animation = new TranslateAnimation(offset, one, 0, 0);
23 } else if (currIndex == 2) {
24 animation = new TranslateAnimation(two, one, 0, 0);
25 }
26 break;
27 case 2:
28 if (currIndex == 0) {
29 animation = new TranslateAnimation(offset, two, 0, 0);
30 } else if (currIndex == 1) {
31 animation = new TranslateAnimation(one, two, 0, 0);
32 }
33 break;
34 }
35 currIndex = arg0;
36 animation.setFillAfter(true);// True:图片停在动画结束位置
37 animation.setDuration(300);
38 cursor.startAnimation(animation);
39 }
40
41 @Override
42 public void onPageScrolled(int arg0, float arg1, int arg2) {
43 }
44
45 @Override
46 public void onPageScrollStateChanged(int arg0) {
47 }
48 }
五、打完收工,快来看看自己的劳动成果吧
源码分享:http://115.com/file/dpi0unyg
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。 各大安卓市场专业刷量,QQ346981595
==========================================
文章出处: http://blog.csdn.net/zhouyuanjing/article/details/8290454
开篇
首页只是作为ViewPager,ViewFlipper,ViewFlow的入口,提供三个Button进行跳转。
1. ViewPager
先看看官方文档怎么介绍ViewPager的:http://developer.android.com/reference/android/support/v4/view/ViewPager.html
继承关系如下:
java.lang.Object
android.view.View
android.view.ViewGroup
android.support.v4.view.ViewPager
ViewPager做为容器类,可以结合View(Layout)和Fragment(Android 3.0 才引入的),官方文档说ViewPager+Fragment配合使用更好。ViewPager不在android sdk 自带jar包中,来源google 的补充组件android-support-v4.jar,没有的话可以通过eclipse下载和自己下载再添加到相应的工程中,本例用的是android-support-v13.jar,完全兼容android-support-v4.jar,看看android-support-v13.jar的目录结构:
[android-support-v13.jar下载]
切入正题,ViewPager用法如下:
配置文件:viewpager_layout.xml:
- <?xml version="1.0" encoding="utf-8"?>
- <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent" >
-
- <android.support.v4.view.ViewPager
- android:id="@+id/viewpager"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content" />
-
- </RelativeLayout>
源文件如下ViewPagerActivity.java如下:
- package com.xyz.vvv.ViewPager;
-
- import java.util.ArrayList;
-
- import com.xyz.vvv.R;
-
- import android.app.ActionBar;
- import android.app.ActionBar.LayoutParams;
- import android.app.ActionBar.Tab;
- import android.app.ActionBar.TabListener;
- import android.app.Activity;
- import android.app.Fragment;
- import android.app.FragmentTransaction;
- import android.content.Context;
- import android.os.Bundle;
- import android.support.v13.app.FragmentPagerAdapter;
- import android.support.v4.view.ViewPager;
- import android.support.v4.view.ViewPager.OnPageChangeListener;
- import android.view.LayoutInflater;
- import android.view.View;
-
- public class ViewPagerActivity extends Activity {
-
- private ViewPager mViewPager;
- private ViewPagerAdapter mAdapter;
- private ActionBar mTabBar;
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
-
- super.onCreate(savedInstanceState);
- setContentView(R.layout.viewpager_layout);
-
- mViewPager = (ViewPager) findViewById(R.id.viewpager);
- mAdapter = new ViewPagerAdapter(this, mViewPager);
- mTabBar = getActionBar();
-
- mAdapter.addTab(mTabBar.newTab().setIcon(R.drawable.tab_icon_qworld),
- FirstFragment.class, null);
- mAdapter.addTab(mTabBar.newTab().setIcon(R.drawable.tab_icon_group),
- SecondFragment.class, null);
- mAdapter.addTab(mTabBar.newTab().setIcon(R.drawable.tab_icon_friends),
- ThreeFragment.class, null);
- mAdapter.addTab(mTabBar.newTab().setIcon(R.drawable.tab_icon_recent),
- FourFragment.class, null);
-
- }
-
- private View getCustomView() {
- return getLayoutInflater().inflate(R.layout.title_panel_layout, null);
- }
-
- private static class ViewPagerAdapter extends FragmentPagerAdapter
- implements TabListener, OnPageChangeListener {
-
- private Context mContext;
- private ActionBar mActionBar = null;
- private ViewPager mViewPager = null;
- private ArrayList<TabInfo> mTabList = new ArrayList<TabInfo>();
-
- public ViewPagerAdapter(Activity activity, ViewPager viewPager) {
-
- super(activity.getFragmentManager());
- mContext = activity;
- mActionBar = activity.getActionBar();
-
-
-
-
- mActionBar.setDisplayOptions(mActionBar.getDisplayOptions()
- ^ ActionBar.DISPLAY_SHOW_HOME
- ^ ActionBar.DISPLAY_SHOW_TITLE, ActionBar.DISPLAY_SHOW_HOME
- | ActionBar.DISPLAY_SHOW_TITLE);
- mActionBar.setDisplayShowHomeEnabled(false);
- mActionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
- mViewPager = viewPager;
- mViewPager.setAdapter(this);
- mViewPager.setOnPageChangeListener(this);
- }
-
-
- @Override
- public void onPageScrollStateChanged(int arg0) {
-
-
- }
-
- @Override
- public void onPageScrolled(int position, float positionOffset,
- int positionOffsetPixels) {
-
-
- }
-
- @Override
- public void onPageSelected(int position) {
-
- mActionBar.setSelectedNavigationItem(position);
- }
-
-
-
-
- @Override
- public void onTabSelected(Tab tab, FragmentTransaction ft) {
-
- Object tag = tab.getTag();
- for (int i = 0; i < mTabList.size(); i++) {
- if (mTabList.get(i) == tag) {
- mViewPager.setCurrentItem(i);
- }
- }
- }
-
- @Override
- public void onTabUnselected(Tab tab, FragmentTransaction ft) {
-
-
- }
-
- @Override
- public void onTabReselected(Tab tab, FragmentTransaction ft) {
-
-
- }
-
-
-
-
- @Override
- public Fragment getItem(int position) {
-
- TabInfo tab = mTabList.get(position);
- if (tab.fragment == null) {
- tab.fragment = Fragment.instantiate(mContext,
- tab.clazz.getName(), tab.bundle);
- }
- return tab.fragment;
- }
-
- @Override
- public int getCount() {
-
- return mTabList.size();
- }
-
-
-
- private View getCustomView() {
- LayoutInflater inflater = (LayoutInflater) mContext
- .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
- return inflater.inflate(R.layout.title_panel_layout, null);
- }
-
- public void addTab(Tab tab, Class<?> clazz, Bundle bundle) {
- TabInfo tabInfo = new TabInfo(clazz, bundle);
- tab.setTag(tabInfo);
- tab.setTabListener(this);
- mTabList.add(tabInfo);
- mActionBar.addTab(tab);
- notifyDataSetChanged();
- }
-
- private static final class TabInfo {
- private final Class<?> clazz;
- private final Bundle bundle;
- Fragment fragment;
-
- TabInfo(Class<?> clazz, Bundle bundle) {
- this.clazz = clazz;
- this.bundle = bundle;
- }
- }
-
- }
-
- }
里面用到的FirstFragment,SecondFragment,ThreeFragment,FourFragment分别继承Fragment,运行效果如下:
第一个就弄里个TextView,复杂的界面开发者任由发挥了,第二个和第四个都是ListView,第三个ExpandableListView,ListView的使用难点就是写适配器咯,本例是继承BaseAdapter的。ExpandableListView需要一个继承BaseExpandableListAdapter的适配器[不会的请看:ExpandableListView用法]。
2.ViewFlipper
ViewFilpper控件是系统自带控件之一,主要为在同一个屏幕间的切换及设置动画效果,且可以自动播放,用法如下:
配置文件:viewflipper_layout.xml
- <?xml version="1.0" encoding="utf-8"?>
- <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:xyz="http://schemas.android.com/apk/res/com.xyz.vvv"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent" >
-
- <ViewFlipper
- android:id="@+id/viewflipper"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:inAnimation="@anim/slide_in"
- android:outAnimation="@anim/slide_out"
- android:flipInterval="2000" >
-
- <include layout="@layout/viewflipper_one_layout" />
-
- <include layout="@layout/viewflipper_two_layout" />
-
- <include layout="@layout/viewflipper_three_layout" />
-
- <include layout="@layout/viewflipper_four_layout" />
-
- <include layout="@layout/viewflipper_five_layout" />
- </ViewFlipper>
-
- <!--
- <com.xyz.vvv.PageControlView
- android:id="@+id/viewflipper_indicator"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:layout_marginBottom="25dip"
- android:gravity="center_horizontal"
- android:layout_alignParentBottom="true"
- xyz:cell_width="@dimen/indicator_width"
- xyz:cell_height="@dimen/indicator_height" />
- -->
-
- </RelativeLayout>
被注释的部分是指示器,那五个layout里都是一个ImageView,本例图片中画有指示器,PageControlView就不需要啦。
android:autoStart="true" <<==>> mViewFlipper.startFlipping(); //自动播放
android:flipInterval="2000" <<==>>mViewFlipper.setFilpInterval(2000); //设置View之间切换的时间间隔
android:inAnimation="@anim/slide_in", android:outAnimation="@anim/slide_out" 对应方法:mViewFlipper.setInAnimation,
mViewFlipper.setOutAnimation。
源文件:ViewFlipperActivity.java
- package com.xyz.vvv.ViewFlipper;
-
- import com.xyz.vvv.R;
-
- import android.app.Activity;
- import android.os.Bundle;
- import android.view.GestureDetector;
- import android.view.GestureDetector.OnGestureListener;
- import android.view.MotionEvent;
- import android.view.View;
- import android.view.View.OnTouchListener;
- import android.widget.ViewFlipper;
-
- public class ViewFlipperActivity extends Activity implements OnGestureListener,
- OnTouchListener {
-
- private ViewFlipper mViewFlipper;
- private GestureDetector mGestureDetector;
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
-
- super.onCreate(savedInstanceState);
- setContentView(R.layout.viewflipper_layout);
-
- mGestureDetector = new GestureDetector(this);
- mViewFlipper = (ViewFlipper) findViewById(R.id.viewflipper);
- mViewFlipper.setOnTouchListener(this);
- mViewFlipper.startFlipping();
- }
-
- @Override
- public boolean onDown(MotionEvent e) {
-
- return false;
- }
-
- @Override
- public void onShowPress(MotionEvent e) {
-
-
- }
-
- @Override
- public boolean onSingleTapUp(MotionEvent e) {
-
- return false;
- }
-
- @Override
- public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
- float distanceY) {
-
- return false;
- }
-
- @Override
- public void onLongPress(MotionEvent e) {
-
-
- }
-
- @Override
- public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
- float velocityY) {
-
- if (e2.getX() - e1.getX() > 0) {
-
- } else {
-
- }
- return true;
- }
-
- @Override
- public boolean onTouch(View v, MotionEvent event) {
-
- mGestureDetector.onTouchEvent(event);
- return true;
- }
-
- }
效果图如下:
图片太宽了,还有一张没加进来(图片来自手机QQ)。
这是ViewFlipper静态加载View,动态加载View请看:ViewFlipper动态加载View
3.ViewFlow
Viewflow 是 Android 平台上一个视图切换的效果库,非标准的得自己下载。ViewFlow 相当于 Android UI 部件提供水平滚动的 ViewGroup,使用 Adapter 进行条目绑定。这个拿来主义 ^-^
按图说话吧: 带圆点的指示器。
配置文件:circle_viewflow_layout.xml
- <?xml version="1.0" encoding="utf-8"?>
- <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:xyz="http://schemas.android.com/apk/res/com.xyz.vvv"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:orientation="vertical" >
-
- <org.taptwo.android.widget.ViewFlow
- android:id="@+id/viewflow"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- xyz:sidebuffer="3" >
- </org.taptwo.android.widget.ViewFlow>
-
- <org.taptwo.android.widget.CircleFlowIndicator
- android:id="@+id/viewflowindic"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_gravity="bottom|center_horizontal"
- android:padding="10dip"
- android:layout_marginBottom="10dip"
- xyz:fadeOut="1000"
- xyz:inactiveType="stroke" />
-
- </FrameLayout>
源文件:CircleViewFlowActivity.java
- package com.xyz.vvv.ViewFlow;
-
- import org.taptwo.android.widget.CircleFlowIndicator;
- import org.taptwo.android.widget.ViewFlow;
-
- import com.xyz.vvv.R;
-
- import android.app.Activity;
- import android.content.Context;
- import android.content.res.Configuration;
- import android.os.Bundle;
- import android.view.LayoutInflater;
- import android.view.View;
- import android.view.ViewGroup;
- import android.widget.BaseAdapter;
- import android.widget.ImageView;
-
- public class CircleViewFlowActivity extends Activity {
-
- private ViewFlow mViewFlow;
- private CircleFlowIndicator mIndicator = null;
-
-
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setTitle(R.string.circle_title);
- setContentView(R.layout.circle_viewflow_layout);
-
- mViewFlow = (ViewFlow) findViewById(R.id.viewflow);
- mViewFlow.setAdapter(new ViewFlowAdapter(this), 0);
- mIndicator = (CircleFlowIndicator) findViewById(R.id.viewflowindic);
- mViewFlow.setFlowIndicator(mIndicator);
- }
-
- @Override
- public void onConfigurationChanged(Configuration newConfig) {
- super.onConfigurationChanged(newConfig);
- mViewFlow.onConfigurationChanged(newConfig);
- }
-
- private class ViewFlowAdapter extends BaseAdapter {
-
- private Context mContext;
- private LayoutInflater mInflater = null;
- private final int[] mImageIds = { R.drawable.cupcake, R.drawable.donut,
- R.drawable.eclair, R.drawable.froyo, R.drawable.gingerbread,
- R.drawable.honeycomb, R.drawable.icecream };
-
- public ViewFlowAdapter(Context ctx) {
- mContext = ctx;
- mInflater = (LayoutInflater) mContext
- .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
- }
-
- @Override
- public int getCount() {
-
- return mImageIds.length;
- }
-
- @Override
- public Integer getItem(int position) {
-
- return mImageIds[position];
- }
-
- @Override
- public long getItemId(int position) {
-
- return position;
- }
-
- @Override
- public View getView(int position, View convertView, ViewGroup parent) {
-
- if (convertView == null) {
- convertView = mInflater.inflate(R.layout.circle_viewflow_item_layout,
- null);
- }
- ((ImageView) convertView.findViewById(R.id.img_view))
- .setImageResource(getItem(position));
- return convertView;
- }
-
- }
- }
ViewFlow还有其他几个例子,个人觉得用的不多,就不贴啦,感兴趣的可以下载下来研究下。
源码下载:http://download.csdn.net/detail/zhouyuanjing/4886174
~~完~~