养成习惯,做过代码记录总结。

ViewPager 使用记录

1. ViewPage 位于V4包。

2.主要用来做banner轮播。

3.原理:适配器重用提高效率,与listview等一个原理。

下面记录实现代码。

一:

在布局里使用ViewPager

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
tools:context="com.example.testviewpage_1.MainActivity" > <android.support.v4.view.ViewPager
android:id="@+id/viewpager"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center" />
</RelativeLayout>

二:需要一个适配器 :PageAdapter ;

 PagerAdapter pagerAdapter = new PagerAdapter() {

        @Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == arg1;
} @Override
public int getCount() {
return viewList.size();
} @Override
public void destroyItem(ViewGroup container, int position,
Object object) {
container.removeView(viewList.get(position));
} @Override
public Object instantiateItem(ViewGroup container, int position) {
container.addView(viewList.get(position));
return viewList.get(position);
}
};

三:给apapter 加点数据(View)。

private ViewPager viewPager;

private List<View> viewList;
 viewList = new ArrayList<>();
ImageView iv = new ImageView(getActivity());
Glide.with(getContext()).load("http://www.shjinheng.com/uploadfile/2016/1130/20161130023058307.jpg").into(iv);
viewList.add(iv);
iv = new ImageView(getActivity());
Glide.with(getContext()).load(urls[1]).into(iv);
viewList.add(iv);
iv = new ImageView(getActivity());
Glide.with(getContext()).load(urls[2]).into(iv);
viewList.add(iv);

关键内容:

对adapter的里解

Base class providing the adapter to populate pages inside of a ViewPager. You will most likely want to use a more specific implementation of this, such as FragmentPagerAdapter orFragmentStatePagerAdapter.

When you implement a PagerAdapter, you must override the following methods at minimum:

instantiateItem(ViewGroup, int)
destroyItem(ViewGroup, int, Object)
getCount()
isViewFromObject(View, Object)
PagerAdapter is more general than the adapters used for AdapterViews. Instead of providing a View recycling mechanism directly ViewPager uses callbacks to indicate the steps taken during an update. A PagerAdapter may implement a form of View recycling if desired or use a more sophisticated method of managing page Views such as Fragment transactions where each page is represented by its own Fragment. ViewPager associates each page with a key Object instead of working with Views directly. This key is used to track and uniquely identify a given page independent of its position in the adapter. A call to the PagerAdapter method startUpdate(ViewGroup) indicates that the contents of the ViewPager are about to change. One or more calls to instantiateItem(ViewGroup, int) and/ordestroyItem(ViewGroup, int, Object) will follow, and the end of an update will be signaled by a call to finishUpdate(ViewGroup). By the time finishUpdate returns the views associated with the key objects returned by instantiateItem should be added to the parent ViewGroup passed to these methods and the views associated with the keys passed to destroyItem should be removed. The method isViewFromObject(View, Object) identifies whether a page View is associated with a given key object. A very simple PagerAdapter may choose to use the page Views themselves as key objects, returning them from instantiateItem(ViewGroup, int) after creation and adding them to the parent ViewGroup. A matching destroyItem(ViewGroup, int, Object) implementation would remove the View from the parent ViewGroup and isViewFromObject(View, Object) could be implemented as return view == object;. PagerAdapter supports data set changes. Data set changes must occur on the main thread and must end with a call to notifyDataSetChanged() similar to AdapterView adapters derived fromBaseAdapter. A data set change may involve pages being added, removed, or changing position. The ViewPager will keep the current page active provided the adapter implements the methodgetItemPosition(Object).
isViewFromObject(View, Object)

功能:该函数用来判断instantiateItem(ViewGroup, int)函数所返回来的Key与一个页面视图是否是代表的同一个视图(即它俩是否是对应的,对应的表示同一个View)

返回值:如果对应的是同一个View,返回True,否则返回False。

instantiateItem (ViewGroup container, int position)

给对应位置一个View

实现循环

有两种办法,一种是把getcount改成

Integer.MAX_VALUE
在dinstantiateItem 方法中 对position取%
然后就是各种坑,这种方法不太好用。
第二种方法是多加两个view 取实际的最后一个放在第一个,实际第一个放在最后一个。
如果是三个数据,那最终viewlist应该是2,0,1,2,0
onPageSelected方法中当页转到第5页时,调用setCurrentItem方法将当前页设置到1,相反是0的时候设置到2;
看代码
      
     多插入两条内容。
     viewList = new ArrayList<>();
ImageView iv = new ImageView(getActivity());
Glide.with(getContext()).load(urls[2
]).into(iv);
viewList.add(iv);//多加的

iv = new ImageView(getActivity());
Glide.with(getContext()).load(urls[0]).into(iv);
viewList.add(iv); iv = new ImageView(getActivity());
Glide.with(getContext()).load(urls[1]).into(iv);
viewList.add(iv); iv = new ImageView(getActivity());
Glide.with(getContext()).load(urls[2]).into(iv);
viewList.add(iv); iv = new ImageView(getActivity());
Glide.with(getContext()).load(urls[0]).into(iv);
viewList.add(iv);//多加的
     viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override
public void onPageSelected(final int position) {
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
if (position == viewList.size() - 1) {
viewPager.setCurrentItem(1, false);//不要动画
} else if (position == 0) {
viewPager.setCurrentItem(viewList.size() - 2, false);//不要动画
}
}
}, 200);//延后执行,改善视觉效果。 } @Override
public void onPageScrollStateChanged(int state) { }
});

当然要从第二个开始展示

viewPager.setCurrentItem(1);

接下来搞定自动轮播:
handler 来实现。
 Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
viewPager.setCurrentItem((viewPager.getCurrentItem() + 1) % viewList.size());
mHandler.sendEmptyMessageDelayed(1, 1000);
}
};
修改滑动速度.
默认的速度太快,viewpager也没有给出修改办法,还限制了最长不超过600毫秒。
滑动最终还是由scroller完成,我们通过反射来修改viewpager自带scroller ;
package com.lechang.utils;

import android.content.Context;
import android.support.v4.view.ViewPager;
import android.view.animation.Interpolator;
import android.widget.Scroller; import java.lang.reflect.Field; /**
* hongtao
*/
public class MyScroller extends Scroller { private int mDuration = 1500; // default time is 1500ms public MyScroller(Context context) {
super(context);
} public MyScroller(Context context, Interpolator interpolator) {
super(context, interpolator);
} @Override
public void startScroll(int startX, int startY, int dx, int dy, int duration) {
super.startScroll(startX, startY, dx, dy, mDuration);
} @Override
public void startScroll(int startX, int startY, int dx, int dy) {
super.startScroll(startX, startY, dx, dy, mDuration);
} /**
* set animation time
*
* @param time
*/
public void setmDuration(int time) {
mDuration = time;
} /**
* get current animation time
*
* @return
*/
public int getmDuration() {
return mDuration;
} public void acttchToViewPager(ViewPager viewPager) {
try {
Field mField = ViewPager.class.getDeclaredField("mScroller");
mField.setAccessible(true);
mField.set(viewPager, this);
} catch (Exception e) {
e.printStackTrace();
}
}
}
//修改滑动速度
MyScroller myScroller = new MyScroller(getContext());
myScroller.setmDuration(2000);
myScroller.attacToViewPager(viewPager); 到此完美实现。 给出完整的类:
package com.lechang.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout; import com.bumptech.glide.Glide;
import com.lechang.R;
import com.lechang.utils.MyScroller; import java.util.ArrayList;
import java.util.List; /**
* @author hongtao
*/
public class QualityFragment extends BaseFragment { public QualityFragment() { } @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_quality, container, false);
init(view);
return view;
} LinearLayout ll_point; String urls[] = {"https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=150174610,1151432426&fm=27&gp=0.jpg",
"https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=1705520648,1030222030&fm=27&gp=0.jpg",
"https://f10.baidu.com/it/u=2987595138,4271236850&fm=72"}; public void setPoint(int index) {
if (index == viewList.size() - 1) {
index = 1;
} else if (index == 0) {
index = viewList.size() - 2;
}
for (int i = 0; i < viewList.size() - 1; i++) {
if (i == (index - 1)) {
ll_point.getChildAt(i).setBackgroundResource(R.drawable.point_fucsed);
} else {
ll_point.getChildAt(i).setBackgroundResource(R.drawable.point_unfucsed);
}
}
} public void initPoint() {
for (int i = viewList.size() - 2; i < ll_point.getChildCount(); i++) {
ll_point.getChildAt(i).setVisibility(View.GONE);
}
} public void init(View rootView) {
ll_point = (LinearLayout) rootView.findViewById(R.id.ll_point);
viewList = new ArrayList<>();
ImageView iv = new ImageView(getActivity());
Glide.with(getContext()).load(urls[2]).into(iv);
viewList.add(iv); iv = new ImageView(getActivity());
Glide.with(getContext()).load(urls[0]).into(iv);
viewList.add(iv); iv = new ImageView(getActivity());
Glide.with(getContext()).load(urls[1]).into(iv);
viewList.add(iv); iv = new ImageView(getActivity());
Glide.with(getContext()).load(urls[2]).into(iv);
viewList.add(iv); iv = new ImageView(getActivity());
Glide.with(getContext()).load(urls[0]).into(iv);
viewList.add(iv); viewPager = (ViewPager) rootView.findViewById(R.id.viewpager);
viewPager.setAdapter(pagerAdapter);
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override
public void onPageSelected(final int position) {
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
if (position == viewList.size() - 1) {
viewPager.setCurrentItem(1, false);//不要动画
} else if (position == 0) {
viewPager.setCurrentItem(viewList.size() - 2, false);//不要动画
}
}
}, INTERVAL_TIME);//延后执行,改善视觉效果。
setPoint(position);
} @Override
public void onPageScrollStateChanged(int state) { }
});
viewPager.setCurrentItem(1);
initPoint();
//修改滑动速度
MyScroller myScroller = new MyScroller(getContext());
myScroller.setmDuration(2000);
myScroller.attachToViewPager(viewPager); mHandler.sendEmptyMessageDelayed(1, INTERVAL_TIME);
} public static final int INTERVAL_TIME = 3000;
Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
viewPager.setCurrentItem((viewPager.getCurrentItem() + 1) % viewList.size());
mHandler.sendEmptyMessageDelayed(1, INTERVAL_TIME);
}
}; private ViewPager viewPager; private List<View> viewList; PagerAdapter pagerAdapter = new PagerAdapter() { @Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == arg1;
} @Override
public int getCount() {
return viewList.size();
} @Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView(viewList.get(position));
} @Override
public Object instantiateItem(ViewGroup container, int position) {
container.addView(viewList.get(position));
return viewList.get(position);
}
}; }
配置
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.lechang.fragment.QualityFragment"> <RelativeLayout
android:layout_width="match_parent"
android:layout_height="150dp"> <android.support.v4.view.ViewPager
android:id="@+id/viewpager"
android:layout_width="match_parent"
android:layout_height="150dp"
android:background="#444" /> <LinearLayout
android:id="@+id/ll_point"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"> <View
android:layout_width="5dp"
android:layout_height="5dp"
android:layout_margin="5dp"
android:background="@drawable/point_fucsed" /> <View
android:layout_width="5dp"
android:layout_height="5dp"
android:layout_margin="5dp"
android:background="@drawable/point_unfucsed" /> <View
android:layout_width="5dp"
android:layout_height="5dp"
android:layout_margin="5dp"
android:background="@drawable/point_unfucsed" /> <View
android:layout_width="5dp"
android:layout_height="5dp"
android:layout_margin="5dp"
android:background="@drawable/point_unfucsed" /> <View
android:layout_width="5dp"
android:layout_height="5dp"
android:layout_margin="5dp"
android:background="@drawable/point_unfucsed" />
</LinearLayout>
</RelativeLayout> </FrameLayout>
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval"
android:useLevel="false"> <solid android:color="#055" />
<stroke
android:width="1dp"
android:color="@color/white" />
<size
android:width="5dp"
android:height="5dp" />
</shape>
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval"
android:useLevel="false"> <solid android:color="#f00" />
<stroke
android:width="1dp"
android:color="@color/white" />
<size
android:width="5dp"
android:height="5dp" />
</shape>

                  

ViewPager +无限轮播+滑动速度修改+指示小点的更多相关文章

  1. ViewPager无限轮播与自定义切换动画

    一直在寻求一个能用得长久的ViewPager,寻寻觅觅终于发现,ViewPager有这一个就够了. 注:并非完全原创 先看一下效果: 淡入淡出: 旋转: 无限轮播的ViewPager 主要设计思路(以 ...

  2. 踩石行动:ViewPager无限轮播的坑

    2016-6-19 前言 View轮播效果在app中很常见,一想到左右滑动的效果就很容易想到使用ViewPager来实现.对于像我们常说的banner这样的效果,具备无限滑动的功能是可以用ViewPa ...

  3. ViewPager实现无限轮播踩坑记

    最近笔者想通过ViewPager来实现一个广告Banner,并实现无限轮播的效果,但是在这个过程中踩了不少的坑,听我慢慢道来.如果大家有遇到和我一样的情况,可以参考我的解决方法,没有那就更好,如果针对 ...

  4. 利用RecyclerView实现无限轮播广告条

    代码地址如下:http://www.demodashi.com/demo/14771.html 前言: 公司产品需要新增悬浮广告条的功能,要求是可以循环滚动,并且点击相应的浮条会跳转到相应的界面,在实 ...

  5. iOS开发之ImageView复用实现图片无限轮播

    在上篇博客中iOS开发之多图片无缝滚动组件封装与使用给出了图片无限轮播的实现方案之一,下面在给出另一种解决方案.今天博客中要说的就是在ScrollView上贴两个ImageView, 把ImageVi ...

  6. Android真正意义上的无限轮播Banner

    在android开发的时候,经常会使用到轮播图,对于这种效果,一般情况下,我们都会使用一种叫做ViewPager的来实现. 传统的实现逻辑是自定义一个View继承ViewPager,在适配器中 将co ...

  7. ViewPage实现无限轮播画廊效果

    1. 效果图 2. 布局文件 主要使用的 android:clipChildren的意思:是否限制子View在其范围内.再父布局和viewpager中设置该属性  ,要显示三个界面 ,还要设置marg ...

  8. iOS开发之三个Button实现图片无限轮播(参考手机淘宝,Swift版)

    这两天使用Reveal工具查看"手机淘宝"App的UI层次时,发现其图片轮播使用了三个UIButton的复用来实现的图片循环无缝滚动.于是乎就有了今天这篇博客,看到“手机淘宝”这个 ...

  9. Android使用ViewPager做轮播

    ViewPager.html div.oembedall-githubrepos { border: 1px solid #DDD; list-style-type: none; margin: 0 ...

随机推荐

  1. vue——实例方法 / 数据

    目录 1.vm.$set 2.vm.$watch 3.vm.$delete 1.vm.$set 哎呀呀,周五啦,大家应该都很开心吧,放假了可以好好休息休息啦,然而小颖明天要面试,所以小颖今天就回去放了 ...

  2. 【NOIP2015提高组】 Day1 T2 信息传递

    题目描述 有n个同学(编号为1到n)正在玩一个信息传递的游戏.在游戏里每人都有一个固定的信息传递对象,其中,编号为i的同学的信息传递对象是编号为Ti同学. 游戏开始时,每人都只知道自己的生日.之后每一 ...

  3. (转)关于Tomcat的点点滴滴(体系架构、处理http请求的过程、安装和配置、目录结构、设置压缩和对中文文件名的支持、以及Catalina这个名字的由来……等)

    转自:http://itfish.net/article/41668.html   总结Tomcat的体系架构.处理http请求的过程.安装和配置.目录结构.设置压缩和对中文文件名的支持.以及Cata ...

  4. windows消息简单应用实例

    //基本定义 internal class MyMessager : IMessageFilter { public bool PreFilterMessage(ref Message m) { // ...

  5. Linux系统fdisk分区

    以下操作全部基于win7 64位系统上的Linux虚拟机(CentOS6.6). 当Linux虚拟机的硬盘空间不够用时,可以手动添加硬盘块,流程如下: 右键虚拟机,点击“Add”按钮: 选择“Hard ...

  6. 动态主机配置协议DHCP

    一.什么是DHCP DHCP,动态主机配置协议,提供一种称为“即插即用连网”的机制,允许一台计算机加入新的网络和获取IP地址而不用手工配置. 二.DHCP工作原理和工作流程 DHCP服务器被动打开UD ...

  7. 通过Struts了解MVC框架,兼说如何在面试中利用Struts证明自己

    虽然目前Struts MVC框架不怎么用了,但它确是个能帮助大家很好地入门Web MVC框架,而且,一些历史项目可能还用Struts,反正技多不压身,大家如果能在面试中通过项目证明自己Struts这块 ...

  8. Python 爬虫:把廖雪峰教程转换成 PDF 电子书

    写爬虫似乎没有比用 Python 更合适了,Python 社区提供的爬虫工具多得让你眼花缭乱,各种拿来就可以直接用的 library 分分钟就可以写出一个爬虫出来,今天尝试写一个爬虫,将廖雪峰老师的 ...

  9. RabbitMQ-客户端

    Install-Package RabbitMQ.Client 参考: http://www.rabbitmq.com/download.html https://www.nuget.org/pack ...

  10. 修改文件的所有者失(chown: changing ownership of `uploads': Operation not permitted)

    在项目开发的时候,经常需要将文件上传到指定的目录下. 例如这次用thinkphp5的时候,需要在public目录下建立uploads目录用于存放上传的资源. 首先在命令窗口下输入: mkdir upl ...