1.适配器:
package com.example.adapter; import java.util.ArrayList; import android.annotation.SuppressLint; import android.app.ActionBar.LayoutParams; import android.support.v4.view.PagerAdapter; import android.view.View; import android.view.ViewGroup; public class MyViewPagerAdapter extends PagerAdapter{ private ArrayList<View>mlist; public MyViewPagerAdapter(ArrayList<View>mlist){ super(); this.mlist=mlist; } @Override public int getCount() { // TODO Auto-generated method stub return this.mlist==null?0:this.mlist.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(this.mlist.get(position)); } @SuppressLint("NewApi") public Object instantiateItem(ViewGroup container,int position){ LayoutParams lp=new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT); container.addView(this.mlist.get(position),lp); return this.mlist.get(position); } }
2.activity:
package com.example.adapter; import java.util.ArrayList; import android.app.Activity; import android.os.Bundle; import android.support.v4.view.ViewPager; import android.text.Layout; import android.view.View; import android.view.ViewGroup.LayoutParams; import android.widget.ImageView; import android.widget.ImageView.ScaleType; public class ViewPageActivity extends Activity{ private int[]imgs={ R.drawable.bbe609315da7a9bfa65df713e7c168e0, R.drawable.bc494385774b8343123c5697ebeaeb9, R.drawable.dd6709ab53006f11f393e58f2ba614c4, R.drawable.e8d145de5ffdf97a4407ab4c5dd33513, R.drawable.eecfd0d328203e8a15366658231c3174 }; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.viewpagelayout); ViewPager viewPager=(ViewPager) findViewById(R.id.myPager); ArrayList<View>mlist=new ArrayList<View>(); for(int i=0;i<imgs.length;i++){ ImageView imgView=new ImageView(this); imgView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT)); imgView.setScaleType(ScaleType.FIT_XY); imgView.setImageResource(imgs[i]); mlist.add(imgView); } MyViewPagerAdapter adapter=new MyViewPagerAdapter(mlist); viewPager.setAdapter(adapter); } }