ViewPager是谷歌官方提供给我们兼容低版本软件安卓设备的软件包之一,使用它必须至少实现ViewPager类中的这四个方法:
- public Object instantiateItem(ViewGroup container, int position){}
- public void destroyItem(ViewGroup container, int position,Object object) {return container.remover()}
- public int getCount(){return xx.length}
- public boolean isViewFromObject(View arg0, Object arg1) {return arg0 == arg1}
一、新建布局文件
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:layout_width="match_parent"
android:layout_height="match_parent">
<!-- 要记住前面的包名不能写错 --!>
<android.support.v4.view.ViewPager
android:id="@+id/viewPager"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
</android.support.v4.view.ViewPager>
</RelativeLayout>
二、代码实现
public class MainActivity extends AppCompatActivity {
//初始化图片,ViewPager,List<ImageView>
private int[] images = new int[]{R.mipmap.guide_image1,R.mipmap.guide_image2,R.mipmap.guide_image3};
private ViewPager viewPager;
private List<ImageView> imageViewList = new ArrayList<ImageView>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//
viewPager = (ViewPager) findViewById(R.id.viewPager);
//为viewpager添加切换动画效果
viewPager.setAdapter(new PagerAdapter() {
//instantiateItem():将当前视图添加到container中并返回当前View
@Override
public Object instantiateItem(ViewGroup container, int position) {
ImageView imageView = new ImageView(MainActivity.this);
//设置图片显示,Android Studio中要把高分辨率的图片放入xxhdpi中,否则可能或出现OutOfMemory
imageView.setImageResource(images[position]);
imageView.setScaleType(ImageView.ScaleType.CENTER);
//将图片添加到container中
container.addView(imageView);
imageViewList.add(imageView);
return imageView;
}
//destroyItem():从当前container中删除指定位置(position)的View;
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView(imageViewList.get(position));
}
//getCount():返回要滑动的VIew的个数
@Override
public int getCount() {
return images.length;
}
//官方指定书写,暂时先不了解
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
});
}
}
这是今天在慕课网学习ViewPager中根据老师写的Demo。希望以后多学习,多写博客。