ViewPager的使用

ViewPager可以实现页面的滚动功能,通常配合PagerTabStrip或者PagerTitleStrip一起使用,从而显示标题。如果要使用PagerTabStrip或者PagerTitleStrip的话,需要把它们作为ViewPager的子控件使用,同时应该设置它们的属性layout_gravity为top或者bottom,表示标题显示在顶部或者底部。ViewPager其实只是一个空页面,需要像ListView一样由PagerAdapter提供内容;

当你实现一个PagerAdapter时,至少需要重载以下几个方法:

  • instantiateItem(ViewGroup, int) //初始化,添加一个页面并返回当前页面
  • destroyItem(ViewGroup, int, Object) //移除一个页面
  • getCount() //返回页面的个数
  • isViewFromObject(View, Object) //判断返回的页面与当前所在页面是否相同

当我们使用了PagerTitleStrip或者PagerTabStrip是还需要重载getPageTitle(int position);

示例如下:

布局文件:activity_main.xml



   
       
       
       


tab1.xml:tab2.xml与tab3.xml基本一样,只是其中的id和text不一样;



    


主活动:MainActivity

package com.example.viewpagerdemo;

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

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;


public class MainActivity extends Activity {
	private ViewPager viewPager;
	private ArrayList viewList ;
	private ArrayList titleList;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        viewPager = (ViewPager)findViewById(R.id.viewpager);
        viewList = new ArrayList();
        viewList.add(getLayoutInflater().inflate(R.layout.tab1, null));
        viewList.add(getLayoutInflater().inflate(R.layout.tab2, null));
        viewList.add(getLayoutInflater().inflate(R.layout.tab3, null));
        titleList = new ArrayList();
        titleList.add("语文");
        titleList.add("数学");
        titleList.add("英语");
        PagerAdapter pagerAdapter = new PagerAdapter()
        {

			@Override
			public int getCount() {
				// TODO Auto-generated method stub
				return viewList.size();
			}

			@Override
			public boolean isViewFromObject(View arg0, Object arg1) {
				// TODO Auto-generated method stub
				return arg0 == arg1;
			}
			
			public void destroyItem(ViewGroup container,int position,Object object)
			{
				container.removeView(viewList.get(position));
			}
			
			public Object instantiateItem(ViewGroup container,int position)
			{
				container.addView(viewList.get(position));
				return viewList.get(position);
			}
        	public CharSequence getPageTitle(int position)
        	{
        		return titleList.get(position);
        	}
        };
        viewPager.setAdapter(pagerAdapter);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}
关于 getLayoutInflater()

至于其运行结果虽然可以实现页面的滑动,但是与我们常见的应用却有区别,因为其标题栏也会随着页面的滑动而滑动,给人以一种不和谐的感觉,若要实现标题栏不动的效果,需要自己定义光标;
实现标题栏不动的自定义光标的方法:

示例:

main_activity.xml:



    
    "

其他布局文件与前面的一样;

MainActivity:

package com.example.viewpagercursor;

import java.util.ArrayList;

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.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;


public class MainActivity extends Activity {
	private ArrayList viewContainer;
	private ViewPager viewPager;
	private ImageView cursor;
	
	private int bmpw = 0; //保存图片的宽度
	private int offest = 0;   //偏移
	private int currIndex = 0;  //页面编号
    @SuppressWarnings("deprecation")
	@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        viewPager = (ViewPager)findViewById(R.id.viewpager);
        cursor = (ImageView)findViewById(R.id.cursor);
        viewContainer = new ArrayList();
        
        viewContainer.add(getLayoutInflater().inflate(R.layout.tab1, null));
        viewContainer.add(getLayoutInflater().inflate(R.layout.tab2, null));
        viewContainer.add(getLayoutInflater().inflate(R.layout.tab3, null));
        
        PagerAdapter pagerAdapter = new PagerAdapter()
        {

			@Override
			public int getCount() {
				// TODO Auto-generated method stub
				return viewContainer.size();
			}

			@Override
			public boolean isViewFromObject(View arg0, Object arg1) {
				// TODO Auto-generated method stub
				return arg0 == arg1;
			}
			
			public void destroyItem(ViewGroup container,int position, Object object)
			{
				container.removeView(viewContainer.get(position));
			}
			
			public Object instantiateItem(ViewGroup container,int position)
			{
				container.addView(viewContainer.get(position));
				return viewContainer.get(position);
			}
        	
        };
        initCursor();
        viewPager.setAdapter(pagerAdapter);
        
        viewPager.setOnPageChangeListener(new OnPageChangeListener()
        {
        	int one = offest*2 + bmpw;
        	int two = one *2;
			@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
				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(offest,one,0,0);
					else if(currIndex == 2)
						animation = new TranslateAnimation(two,one,0,0);
					break;
				}
				case 2:
				{
					if(currIndex == 0)
						animation = new TranslateAnimation(offest,two,0,0);
					else if(currIndex == 1)
						animation = new TranslateAnimation(one,two,0,0);
					break;
				}
				}
				currIndex = arg0;
				animation.setFillAfter(true);
				animation.setDuration(300);
				cursor.startAnimation(animation);
			}
        	
        });
    }
    public void initCursor()
    {
    	
    	bmpw = BitmapFactory.decodeResource(getResources(),R.drawable.ic_launcher).getWidth();
    	DisplayMetrics dm = new DisplayMetrics();
    	getWindowManager().getDefaultDisplay().getMetrics(dm);
    	int screenW = dm.widthPixels;
    	offest = (screenW/viewContainer.size()-bmpw)/2;
    	Matrix matrix = new Matrix();
    	matrix.postTranslate(offest, 0);  //水平平移offest
    	cursor.setImageMatrix(matrix);    //设置初始位置
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

关于 Matrix ;

关于Animation  ;

       上面的代码实现了游标的滚动,把一张图片作为游标,其实还可以像其他APP一样实现上面是标题栏,然后是游标,再下面是内容,实现方法差不多,可以参考ViewPager实现多页面滚动以及动画



——每天都要有进步








你可能感兴趣的:(Android)