本帖最后由 liu 于 2018-12-17 14:44 编辑
ViewPager的用法
ViewPager继承自ViewGroup,它的功能是可以使视图滑动,实现多页面的切换
简单举个例子看下用法,几张图片的切换:
首先在主布局中添加ViewPager:
activity_main.xml:
[XML] 纯文本查看 复制代码 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<android.support.v4.view.ViewPager
android:id="@+id/vp"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
然后加载要显示的页卡,这里是放入了三张图片:
[Java] 纯文本查看 复制代码 List<View> list = new ArrayList<>();
int[] imgs = {R.drawable.img1, R.drawable.img2, R.drawable.img3};
ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
for (int i = 0; i < imgs.length; i++) {
// 将图片装载到数组中
ImageView imageView = new ImageView(this);
imageView.setBackgroundResource(imgs[i]);
imageView.setLayoutParams(layoutParams);
list.add(imageView);
}
最后设置适配器:
[Java] 纯文本查看 复制代码 package com.company.helloworld.firstapplication;
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import java.util.List;
/**
* Created by Administrator on 2018/12/17.
*/
public class MyAdapter extends PagerAdapter {
private Context context;
private List<View> list;
public MyAdapter(Context context, List<View> list) {
this.context = context;
this.list = list;
}
//返回的数量
@Override
public int getCount() {
return list.size();
}
//删除页卡
@Override
public void destroyItem(ViewGroup arg0, int arg1, Object arg2) {
arg0.removeView(list.get(arg1));
}
//添加页卡
@Override
public Object instantiateItem(ViewGroup arg0, int arg1) {
arg0.addView(list.get(arg1), 0);
return list.get(arg1);
}
@Override
public boolean isViewFromObject(View view, Object object) {
return (view == object);
}
}
看下运行效果:
|