android: ViewPager滑动切换Activity

ViewPager非常适合用于实现多页面的滑动切换效果
相同的多页面切换可以是TabHost,但是tabhost标题栏需要重写,稍微麻烦一点
所以采用ViewPager来实现滑动切换,网上很多都是使用ViewPager来加载View,做一些静态的页面展示,像导航,图片展示,使用教程等等
下面实现ViewPager滑动切换Activity
 由于是Google的兼容包类库所以一定要在工程中导入  android-support-v4.jar

效果图

 

切换的时候非常流畅。

下面上主要的代码。

主页布局 activity_main.xml

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 3     android:layout_width="match_parent"
 4     android:layout_height="match_parent"
 5     android:background="#EEEEEE"
 6     android:orientation="vertical" >
 7 
 8     <LinearLayout
 9         android:id="@+id/linearLayout1"
10         android:layout_width="fill_parent"
11         android:layout_height="40.0dip"
12         android:background="#EEEEEE" >
13 
14         <TextView
15             android:id="@+id/text1"
16             android:layout_width="fill_parent"
17             android:layout_height="fill_parent"
18             android:layout_weight="1.0"
19             android:gravity="center"
20             android:text="标题1"
21             android:textColor="#000000"
22             android:textSize="18.0dip" />
23 
24         <TextView
25             android:id="@+id/text2"
26             android:layout_width="fill_parent"
27             android:layout_height="fill_parent"
28             android:layout_weight="1.0"
29             android:gravity="center"
30             android:text="标题2"
31             android:textColor="#000000"
32             android:textSize="18.0dip" />
33 
34         <TextView
35             android:id="@+id/text3"
36             android:layout_width="fill_parent"
37             android:layout_height="fill_parent"
38             android:layout_weight="1.0"
39             android:gravity="center"
40             android:text="标题3"
41             android:textColor="#000000"
42             android:textSize="18.0dip" />
43     </LinearLayout>
44 
45     <ImageView
46         android:id="@+id/cursor"
47         android:layout_width="fill_parent"
48         android:layout_height="wrap_content"
49         android:background="#EEEEEE"
50         android:scaleType="matrix"
51         android:src="@drawable/roller" />
52 
53     <android.support.v4.view.ViewPager
54         android:id="@+id/viewpage"
55         android:layout_width="match_parent"
56         android:layout_height="match_parent" />
57 
58 </LinearLayout>

Activity文件 MainActivity.java

package com.example.testviewpagerandtabhost;

import java.util.ArrayList;
import java.util.List;


import android.os.Bundle;
import android.os.Parcelable;
import android.app.Activity;
import android.app.LocalActivityManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
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.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.TabHost;
import android.widget.TextView;

public class MainActivity extends Activity {

    Context context = null;
    LocalActivityManager manager = null;
    ViewPager pager = null;
    TabHost tabHost = null;
    TextView t1,t2,t3;
    
    private int offset = 0;// 动画图片偏移量
    private int currIndex = 0;// 当前页卡编号
    private int bmpW;// 动画图片宽度
    private ImageView cursor;// 动画图片

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        context = MainActivity.this;
        manager = new LocalActivityManager(this , true);
        manager.dispatchCreate(savedInstanceState);

        InitImageView();
        initTextView();
        initPagerViewer();

    }
    /**
     * 初始化标题
     */
    private void initTextView() {
        t1 = (TextView) findViewById(R.id.text1);
        t2 = (TextView) findViewById(R.id.text2);
        t3 = (TextView) findViewById(R.id.text3);

        t1.setOnClickListener(new MyOnClickListener(0));
        t2.setOnClickListener(new MyOnClickListener(1));
        t3.setOnClickListener(new MyOnClickListener(2));
        
    }
    /**
     * 初始化PageViewer
     */
    private void initPagerViewer() {
        pager = (ViewPager) findViewById(R.id.viewpage);
        final ArrayList<View> list = new ArrayList<View>();
        Intent intent = new Intent(context, A.class);
        list.add(getView("A", intent));
        Intent intent2 = new Intent(context, B.class);
        list.add(getView("B", intent2));
        Intent intent3 = new Intent(context, C.class);
        list.add(getView("C", intent3));

        pager.setAdapter(new MyPagerAdapter(list));
        pager.setCurrentItem(0);
        pager.setOnPageChangeListener(new MyOnPageChangeListener());
    }
    /**
     * 初始化动画
     */
    private void InitImageView() {
        cursor = (ImageView) findViewById(R.id.cursor);
        bmpW = BitmapFactory.decodeResource(getResources(), R.drawable.roller)
        .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);
        cursor.setImageMatrix(matrix);// 设置动画初始位置
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
    /**
     * 通过activity获取视图
     * @param id
     * @param intent
     * @return
     */
    private View getView(String id, Intent intent) {
        return manager.startActivity(id, intent).getDecorView();
    }

    /**
     * Pager适配器
     */
    public class MyPagerAdapter extends PagerAdapter{
        List<View> list =  new ArrayList<View>();
        public MyPagerAdapter(ArrayList<View> list) {
            this.list = list;
        }

        @Override
        public void destroyItem(ViewGroup container, int position,
                Object object) {
            ViewPager pViewPager = ((ViewPager) container);
            pViewPager.removeView(list.get(position));
        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == arg1;
        }

        @Override
        public int getCount() {
            return list.size();
        }
        @Override
        public Object instantiateItem(View arg0, int arg1) {
            ViewPager pViewPager = ((ViewPager) arg0);
            pViewPager.addView(list.get(arg1));
            return list.get(arg1);
        }

        @Override
        public void restoreState(Parcelable arg0, ClassLoader arg1) {

        }

        @Override
        public Parcelable saveState() {
            return null;
        }

        @Override
        public void startUpdate(View arg0) {
        }
    }
    /**
     * 页卡切换监听
     */
    public class MyOnPageChangeListener 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 onPageScrollStateChanged(int arg0) {
            
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
            
        }
    }
    /**
     * 头标点击监听
     */
    public class MyOnClickListener implements View.OnClickListener {
        private int index = 0;

        public MyOnClickListener(int i) {
            index = i;
        }

        @Override
        public void onClick(View v) {
            pager.setCurrentItem(index);
        }
    };
}

然后是page对应的activity和xml文件

例如A.java  a.xml

package com.example.testviewpagerandtabhost;

import android.app.Activity;
import android.os.Bundle;

public class A extends Activity{
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.a);
    }
}
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#FF9900"
    android:orientation="vertical" >


    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:text="AAAAAAAAAAAA" />

</RelativeLayout>

 PagerViewer加载静态View可以很容易实现,一般流程如下

1         mPager = (ViewPager) findViewById(R.id.vPager);
2         listViews = new ArrayList<View>();
3         LayoutInflater mInflater = getLayoutInflater();
4         listViews.add(mInflater.inflate(R.layout.mo1, null));
5         listViews.add(mInflater.inflate(R.layout.mo2, null));
6         listViews.add(mInflater.inflate(R.layout.mo3, null));
7         mPager.setAdapter(new MyPagerAdapter(listViews));
8         mPager.setCurrentItem(0);
9         mPager.setOnPageChangeListener(new MyOnPageChangeListener());

加载Activity需要使用到上面提供的LocalActivityManager类

manager.startActivity(id, intent).getDecorView(); // 一看就知道什么意思..

 

来源:根据网上流传代码修改..

源码:http://download.csdn.net/detail/mathore/4690978

 

posted on 2012-10-26 18:22  mathore  阅读(25958)  评论(4编辑  收藏  举报