4、如果ViewPager是用xml去定义的,需要写上全局的路径,如:
<android.support.v4.view.ViewPager android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/awesomepager"/>
public class AwesomePagerActivity extends Activity { private ViewPager awesomePager; private Context cxt; private AwesomePagerAdapter awesomeAdapter; private LayoutInflater mInflater; private List<View> mListViews; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); cxt = this; awesomeAdapter = new AwesomePagerAdapter(); awesomePager = (ViewPager) findViewById(R.id.awesomepager); awesomePager.setAdapter(awesomeAdapter); mListViews = new ArrayList<View>(); mInflater = getLayoutInflater(); mListViews.add(mInflater.inflate(R.layout.layout1, null)); mListViews.add(mInflater.inflate(R.layout.layout2, null)); mListViews.add(mInflater.inflate(R.layout.layout3, null)); } private class AwesomePagerAdapter extends PagerAdapter{ @Override public int getCount() { return mListViews.size(); } /** * 从指定的position创建page * * @param container ViewPager容器 * @param position The page position to be instantiated. * @return 返回指定position的page,这里不需要是一个view,也可以是其他的视图容器. */ @Override public Object instantiateItem(View collection, int position) { ((ViewPager) collection).addView(mListViews.get(position),0); return mListViews.get(position); } /** * <span style="font-family:'Droid Sans';">从指定的position销毁page</span> * * *<span style="font-family:'Droid Sans';">参数同上</span> */ @Override public void destroyItem(View collection, int position, Object view) { ((ViewPager) collection).removeView(mListViews.get(position)); } @Override public boolean isViewFromObject(View view, Object object) { return view==(object); } @Override public void finishUpdate(View arg0) {} @Override public void restoreState(Parcelable arg0, ClassLoader arg1) {} @Override public Parcelable saveState() { return null; } @Override public void startUpdate(View arg0) {} } }