ViewPager图片切换的简单案例
1)ViewPager类直接继承了ViewGroup类,所有它是一个容器类,可以在其中添加其他的view类。
2)ViewPager类需要一个PagerAdapter适配器类给它提供数据。
向右滑动切换图片
MainActivity
package com.shaoxin.myviewpager; import android.os.Bundle; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity { private ViewPager viewpager; private List<ImageView> imageViewList; private int[] imgId = {R.drawable.a, R.drawable.b, R.drawable.c, R.drawable.d}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); viewpager = (ViewPager) findViewById(R.id.viewpager); imageViewList = new ArrayList<>(); for (int i = 0; i < imgId.length; i++) { ImageView imgview = new ImageView(this); imgview.setBackgroundResource(imgId[i]); imageViewList.add(imgview); } MyAdapter adapter = new MyAdapter(); viewpager.setAdapter(adapter); } private class MyAdapter extends PagerAdapter { @Override public int getCount() { return imageViewList.size(); } @Override public boolean isViewFromObject(View view, Object object) { return view == object; } @Override public Object instantiateItem(ViewGroup container, int position) { container.addView(imageViewList.get(position)); return imageViewList.get(position); } @Override public void destroyItem(ViewGroup container, int position, Object object) { container.removeView(imageViewList.get(position)); } } }
activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.shaoxin.myviewpager.MainActivity"> <android.support.v4.view.ViewPager android:id="@+id/viewpager" android:layout_width="match_parent" android:layout_height="match_parent" /> </RelativeLayout>