1.新建view_pager.xml
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" > <android.support.v4.view.ViewPager android:id="@+id/viewpager" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" /> </RelativeLayout>
2.新建ViewPagerAdapter类,用于ViewPager布局的实例加载适配器;
public class ViewPagerAdapter extends PagerAdapter{ private Context context; private List<View> viewlist; public ViewPagerAdapter( List<View> views,Context context) { this.context = context; this.views = views; }
//重新4个方法
//getCount()返回List<View>的size: @Override public int getCount() { // TODO Auto-generated method stub return views.size(); }
//instantiateItem():将当前view添加到ViewGroup中,并返回当前View @Override public Object instantiateItem(ViewGroup container, int position) { container.addView(views.get(position)); return views.get(position); } //destroyItem():删除当前的View;
@Override public void destroyItem(ViewGroup container, int position, Object object) { container.removeView(views.get(position)); } //isViewFromObject判断当前的View 和 我们想要的Object(值为View) 是否一样;返回 trun / false;
@Override public boolean isViewFromObject(View arg0, Object arg1) { // TODO Auto-generated method stub return (arg0 == arg1); } }
3.创建Guide类,获取View对象,再将view对象放在List<view>中,然后用List<view>放在适配器ViewPagerAdapter中,最后获取ViewPager并为其
public class Guide extends Activity{ private List<View> listView; private ViewPager viewPager; private ViewPagerAdapter vpAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.view_pager); init(); } private void init() { LayoutInflater inflater = LayoutInflater.from(this); listView = new ArrayList<View>(); //获取View对象 View view1 = inflater.inflate(R.layout.view_pager_img1, null); View view2 = inflater.inflate(R.layout.view_pager_img2, null); View view3 = inflater.inflate(R.layout.view_pager_img3, null); View view4 = inflater.inflate(R.layout.view_pager_img4, null); //view对象放在List<view>中 listView.add(view1); listView.add(view2); listView.add(view3); listView.add(view4); //List<view>放在适配器ViewPagerAdapter中 vpAdapter = new ViewPagerAdapter(listView, this); //获取ViewPage,设置适配器; viewPager = (ViewPager) findViewById(R.id.viewpager); viewPager.setAdapter(vpAdapter); } }
4. 创建view_pager_img.xml;
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" > <ImageView android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/guide_background2"/> </LinearLayout>
时间: 2024-12-17 17:02:16