Android用ViewPager实现多页面的切换效果

Android用ViewPager实现多页面的切换效果_第1张图片
Paste_Image.png

说明:

ViewPager用于实现多页面的切换效果,该类存在于Google的兼容包里面,所以在引用时记得在BuilldPath中加入“android-support-v4.jar”

主布局文件

main.xml




    

        
    


其中ViewPager为多页显示控件,PagerTitleStrip用于显示当前页面的标题
主窗口代码:
PagerTitleDemoActivity.java

package com.ns.pager;

import java.util.ArrayList;

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.PagerTitleStrip;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;

public class PagerTitleDemoActivity extends Activity {
    /** Called when the activity is first created. */
    private ViewPager mViewPager;
    private PagerTitleStrip mPagerTitleStrip;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mViewPager = (ViewPager)findViewById(R.id.viewpager);
        mPagerTitleStrip = (PagerTitleStrip)findViewById(R.id.pagertitle);
        
        //将要分页显示的View装入数组中
        LayoutInflater mLi = LayoutInflater.from(this);
        View view1 = mLi.inflate(R.layout.view1, null);
        View view2 = mLi.inflate(R.layout.view2, null);
        View view3 = mLi.inflate(R.layout.view3, null);
        
        //每个页面的Title数据
        final ArrayList views = new ArrayList();
        views.add(view1);
        views.add(view2);
        views.add(view3);
        
        final ArrayList titles = new ArrayList();
        titles.add("tab1");
        titles.add("tab2");
        titles.add("tab3");
        
        //填充ViewPager的数据适配器
        PagerAdapter mPagerAdapter = new PagerAdapter() {
            
            @Override
            public boolean isViewFromObject(View arg0, Object arg1) {
                return arg0 == arg1;
            }
            
            @Override
            public int getCount() {
                return views.size();
            }

            @Override
            public void destroyItem(View container, int position, Object object) {
                ((ViewPager)container).removeView(views.get(position));
            }

            @Override
            public CharSequence getPageTitle(int position) {
                return titles.get(position);
            }

            @Override
            public Object instantiateItem(View container, int position) {
                ((ViewPager)container).addView(views.get(position));
                return views.get(position);
            }
        };
        
        mViewPager.setAdapter(mPagerAdapter);
    }
}

你可能感兴趣的:(Android用ViewPager实现多页面的切换效果)