ViewPager是什么呢?其实它就是个ViewGroup,用法跟ListView类似
xml:
在layout文件文件夹中,创建一个viewPager的布局文件
命名随意,这里叫vp_layout.xml
如下:
就像使用listview一样,现在创建适配器
创建适配器,继承PagerAdapter即可
private class ViewPagerAdapter extends PagerAdapter {
//ViewPager总共有几个页面
@Override
public int getCount() {
return 0;
}
//判断一个页面(View)是否与instantiateItem方法返回的Object一致
@Override
public boolean isViewFromObject(View view, Object object) {
return false;
}
//创建一个页面
@Override
public Object instantiateItem(ViewGroup container, int position) {
return super.instantiateItem(container, position);
}
//销毁一个页面
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
super.destroyItem(container, position, object);
}
}
getCount( ):获得viewpager中有多少个view
destroyItem( ):移除一个给定位置的页面。适配器有责任从容器中删除这个视图。这是为了确保 在finishUpdate(viewGroup)返回时视图能够被移除。
instantiateItem( ):①将给定位置的view添加到ViewGroup(容器)中,创建并显示出来 ②返回一个代表新增页面的Object(key),通常都是直接返回view本身就可以了, 当然你也可以自定义自己的key,但是key和每个view要一一对应的关系
isViewFromObject( ):判断instantiateItem(ViewGroup, int)函数所返回来的Key与一个页面视图是否是 代表的同一个视图(即它俩是否是对应的,对应的表示同一个View),通常我们直接写 return view == object;就可以了,至于为什么要这样讲起来比较复杂,后面有机会进行了解吧 貌似是ViewPager中有个存储view状态信息的ArrayList,根据View取出对应信息的吧!
package com.example.day006.adapter;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.example.day006.R;
import java.util.List;
/**
* ${FENG}
* 2019-07-10
*/
public class ViewPagerAdapter extends PagerAdapter {
private Context context;
private List mData;
public ViewPagerAdapter(Context context, List mData) {
this.context = context;
this.mData = mData;
}
@Override
public int getCount() {
return mData.size();
}
@Override
public boolean isViewFromObject(@NonNull View view, @NonNull Object o) {
return view == o;
}
@NonNull
@Override
public Object instantiateItem(@NonNull ViewGroup container, int position) {
//加载vp的布局
View inflate = View.inflate(context, R.layout.vp_layout, null);
//给布局中的控件赋值
TextView textView = inflate.findViewById(R.id.vp_tv_id);
textView.setText(mData.get(position));
//添加一个布局
container.addView(inflate);
//返回布局
return inflate;
}
@Override
public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
// super.destroyItem(container, position, object);这一句要删除,否则报错
container.removeView((View) object);
}
}
package com.example.day006;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.example.day006.adapter.ViewPagerAdapter;
import java.util.ArrayList;
import java.util.List;
public class ViewPagerActivity extends AppCompatActivity {
private ViewPager vpId;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//去掉自带的bar
//supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_veiw_pager);
//找到vp
vpId = findViewById(R.id.vp_id);
//初始化数据
List list = new ArrayList<>();
for (int i = 0; i < 4; i++) {
list.add("第"+i+"个View");
}
//设置adapter
vpId.setAdapter(new ViewPagerAdapter(this,list));
}
}
ViewPager有个方法叫做:
setPageTransformer(boolean reverseDrawingOrder, PageTransformer transformer) 用于设置ViewPager切换时的动画效果,并且google官方还给出了两个示例(因为使用的是属性动画,所以不兼容3.0以下)。
第一个参数是boolean 代表正序还是反序,第二个是自定义翻页效果.
public class DepthPageTransformer implements ViewPager.PageTransformer {
private static final float MIN_SCALE = 0.75f;
public void transformPage(View view, float position) {
int pageWidth = view.getWidth();
if (position < -1) { // [-Infinity,-1)
// This page is way off-screen to the left.
view.setAlpha(0);
} else if (position <= 0) { // [-1,0]
// Use the default slide transition when moving to the left page
view.setAlpha(1);
view.setTranslationX(0);
view.setScaleX(1);
view.setScaleY(1);
} else if (position <= 1) { // (0,1]
// Fade the page out.
view.setAlpha(1 - position);
// Counteract the default slide transition
view.setTranslationX(pageWidth * -position);
// Scale the page down (between MIN_SCALE and 1)
float scaleFactor = MIN_SCALE
+ (1 - MIN_SCALE) * (1 - Math.abs(position));
view.setScaleX(scaleFactor);
view.setScaleY(scaleFactor);
} else { // (1,+Infinity]
// This page is way off-screen to the right.
view.setAlpha(0);
}
}
}
调用:
//直接设置即可
vpId.setPageTransformer(false,new DepthPageTransformer());
package com.example.day006;
import android.os.CountDownTimer;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Window;
import com.example.day006.adapter.ViewPagerAdapter;
import java.util.ArrayList;
import java.util.List;
public class ViewPagerActivity extends AppCompatActivity {
private ViewPager vpId;
private CountDownTimer timer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//去掉自带的bar
supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_veiw_pager);
//找到vp
vpId = findViewById(R.id.vp_id);
//初始化数据
final List list = new ArrayList<>();
for (int i = 0; i < 4; i++) {
list.add("第"+i+"个View");
}
//设置adapter
vpId.setPageTransformer(false,new DepthPageTransformer());
vpId.setAdapter(new ViewPagerAdapter(this,list));
//安卓自带的定时器方法
timer = new CountDownTimer(100000, 2000) {
int index = 0;
@Override
public void onTick(long millisUntilFinished) {
//设置当前viewpager显示那个页面
vpId.setCurrentItem(index);
++index;
if (index == list.size()){
index = 0;
}
}
@Override
public void onFinish() {
}
};
timer.start();
}
@Override
protected void onDestroy() {
super.onDestroy();
//防止内存溢出
timer.cancel();
}
}
2, onPageSelected(int position)
滑动后显示的页面和滑动前不同,调用
position:选中显示页面的位置
3 ,onPageScrollStateChanged(int state)
页面状态改变时调用
state:当前页面的状态
SCROLL_STATE_IDLE:空闲状态
SCROLL_STATE_DRAGGING:滑动状态
SCROLL_STATE_SETTLING:滑动后滑翔的状态
//直接设置即可
vpId.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
Log.e("vp","滑动中=====position:"+ position + " positionOffset:"+ positionOffset + " positionOffsetPixels:"+positionOffsetPixels);
}
@Override
public void onPageSelected(int position) {
Log.e("vp","显示页改变=====postion:"+ position);
}
@Override
public void onPageScrollStateChanged(int state) {
switch (state) {
case ViewPager.SCROLL_STATE_IDLE:
Log.e("vp","状态改变=====SCROLL_STATE_IDLE====静止状态");
break;
case ViewPager.SCROLL_STATE_DRAGGING:
Log.e("vp","状态改变=====SCROLL_STATE_DRAGGING==滑动状态");
break;
case ViewPager.SCROLL_STATE_SETTLING:
Log.e("vp","状态改变=====SCROLL_STATE_SETTLING==滑翔状态");
break;
}
}
});
ViewPager与Fragment结合使用 ( 重 点 )
与Fragment结合使用其实也一样,只是用Fragment代替原先的View,填充ViewPager;然后就是Adapter不一样,配合Fragment使用的有两个Adapter:FragmentPagerAdapter和FragmentStatePagerAdapter。
相同点:
FragmentPagerAdapter和FragmentStatePagerAdapter都继承自PagerAdapter
不同点:
卸载不再需fragment时,各自采用的处理方法有所不同
ViewPager两个Adapter方法的区别
在destroyItem()方法中,FragmentStatePagerAdapter调用的是remove()方法,适用于页面较多的情况;FragmentPagerAdapter调用的是detach()方法,适用于页面较少的情况。但是有页面数据需要刷新的情况,不管是页面少还是多,还是要用FragmentStatePagerAdapter,否则页面会因为没有重建得不到刷新
创建Fragment及相应的xml布局
public class PagerFragment extends Fragment {
String mContent;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mContent = (String) getArguments().get("content");
View view = inflater.inflate(R.layout.fragment_pager, container, false) ;
TextView textView = (TextView) view.findViewById(R.id.tv);
textView.setText(mContent);
return view;
}
}
final List list = new ArrayList<>();
for (int i = 0; i < 5; i++) {
PagerFragment fragment = new PagerFragment();
Bundle bundle = new Bundle();
bundle.putString("content","第"+i+"个Fragment");
fragment.setArguments(bundle);
list.add(fragment);
}
ViewPager vp = (ViewPager) findViewById(R.id.vp);
// vp.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
// @Override
// public Fragment getItem(int position) {
// return list.get(position);
// }
//
// @Override
// public int getCount() {
// return list.size();
// }
// });
vp.setAdapter(new FragmentStatePagerAdapter(getSupportFragmentManager()) {
@Override
public Fragment getItem(int position) {
return list.get(position);
}
@Override
public int getCount() {
return list.size();
}
});
FragmentStatePagerAdapter
fragment的生命周期会执行
onDestoryView
onDestory
onCreate
onCreateView
fragment会被销毁
适用用 图片预览等多个fragment的情况
FragmentPagerAdapter
onDestoryView
onCreateView
fragment不会被销毁
适用于引导页等少个fragment的情况