1. 布局文件main.xml
<LinearLayout 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:orientation="vertical"
tools:context=".MainActivity">
<!-- 曾把v4.view.ViewPager写成了v4.View.ViewPager,零乱了一个下午。 -->
<android.support.v4.view.ViewPager
android:id="@+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
2. MainActivity.java
package com.sl.viewpager;
import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.app.Activity;
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.LayoutInflater;
import android.view.Menu;
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;
/**
* 通过该Demo对Android的ViewPager控件有一个基本的了解
* ViewPager的一些可能应用场景:
* 1.开机引导界面
* 2.页卡滑动,功能上类似TabHost。
*
*/
public class MainActivity extends Activity {
private ViewPager mViewPager;
private List<View> mTabViewList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initViewPager();
}
private void initViewPager() {
mViewPager = (ViewPager) findViewById(R.id.view_pager);
mTabViewList = new ArrayList<View>();
LayoutInflater inflater = getLayoutInflater();
mTabViewList.add(inflater.inflate(R.layout.tab1, null));
mTabViewList.add(inflater.inflate(R.layout.tab2, null));
mTabViewList.add(inflater.inflate(R.layout.tab3, null));
mViewPager.setAdapter(new ViewPagerAdapter(mTabViewList));
mViewPager.setCurrentItem(0);
}
/**
* Adapter Class
* @author zhangshaoliang
*
*/
private class ViewPagerAdapter extends PagerAdapter {
private List<View> mListView;
public ViewPagerAdapter(List<View> views) {
this.mListView = views;
}
@Override
public int getCount() {
return mListView.size();
}
@Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == arg1;
}
@Override
public Object instantiateItem(View container, int position) {
/*下面的语句注释了就会出现问题*/
((ViewPager) container).addView(mListView.get(position), 0);
return mListView.get(position);
}
@Override
public void destroyItem(View container, int position, Object object) {
((ViewPager) container).removeView(mListView.get(position));
}
}
}