原理圖
ViewPager循環(huán)、自動(dòng)滾動(dòng)讯检,這種效果很常見(jiàn)琐鲁,一般app首頁(yè)都會(huì)有焦點(diǎn)圖、或者用戶引導(dǎo)頁(yè)面人灼。第三方比較好用的我推薦阿里開(kāi)源的UltraViewPager围段,畢竟大公司的,用著放心吧 ?乛?乛?投放。輪子雖好奈泪,不過(guò)自己也還是需要會(huì)寫吧。
有2種方案實(shí)現(xiàn)循環(huán)滾動(dòng)灸芳,一種是在PagerAdapter設(shè)置最大數(shù)量為int最大值涝桅,另一種就是本文實(shí)現(xiàn)的。前一種感覺(jué)有點(diǎn)奇怪烙样,如果不帶自動(dòng)循環(huán)滾動(dòng)的話還可以用冯遂,畢竟用戶一般不會(huì)切換這么多次能看到頭。而對(duì)于循環(huán)滾動(dòng)的話谒获,需要本文的類似思路實(shí)現(xiàn)起來(lái)比較好一點(diǎn)吧蛤肌,原理看上圖即可壁却。例子效果圖在最后。
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.AttrRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
/**
* 封裝的viewpager
* Created by WZH on 2017/12/14.
*/
public class AutoScrollViewPager<T extends PagerAdapter> extends FrameLayout {
private ViewPager viewPager ;
private PagerAdapter mAdapter ;
private LinearLayout mLinearLayout ;
private Context mContext ;
private int pageMargin = 0 ;
private int oldPosition = 0 ; //上一個(gè)位置
private int currentIndex = 1 ; //當(dāng)前位置
private static long time = 3000 ; //自動(dòng)播放時(shí)間
private static boolean autoPlay = true ; //是否自動(dòng)播放
private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
play();
}
};
private Runnable runnable = new Runnable() {
@Override
public void run() {
viewPager.setCurrentItem(++currentIndex);
}
};
public AutoScrollViewPager(@NonNull Context context) {
this(context,null);
}
public AutoScrollViewPager(@NonNull Context context, @Nullable AttributeSet attrs) {
this(context, attrs,0);
}
public AutoScrollViewPager(@NonNull Context context, @Nullable AttributeSet attrs, @AttrRes int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
/**
* 動(dòng)態(tài)添加viewpager和小圓點(diǎn)
*/
private void init() {
mContext = getContext() ;
setLayerType(View.LAYER_TYPE_SOFTWARE, null);
setClipChildren(false);
pageMargin = getResources().getDimensionPixelSize(R.dimen.page_margin);
viewPager = new ViewPager(mContext);
LayoutParams vparams = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT);
vparams.leftMargin = pageMargin * 2;
vparams.rightMargin = pageMargin * 2 ;
viewPager.setLayoutParams(vparams);
addView(viewPager);
mLinearLayout = new LinearLayout(mContext);
LayoutParams params = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
params.gravity = Gravity.BOTTOM ;
mLinearLayout.setGravity(Gravity.CENTER);
mLinearLayout.setOrientation(LinearLayout.HORIZONTAL);
addView(mLinearLayout,params);
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
play();
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
cancel();
}
/**
* 初始化viewpager
*/
private void initViewPager() {
if (mAdapter==null){
return;
}
viewPager.setCurrentItem(currentIndex);
//設(shè)置紅緩存的頁(yè)面數(shù)
viewPager.setOffscreenPageLimit(1);
// 設(shè)置2張圖之前的間距裸准。
viewPager.setPageMargin(pageMargin);
// viewPager.setPageTransformer(true, new ZoomOutPageTransformer());
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset,int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
if (position==0){
currentIndex = mAdapter.getCount()-2 ;
}else if (position == mAdapter.getCount()-1){
currentIndex = 1 ;
}else {
currentIndex = position ;
}
//此處currentIndex是從1開(kāi)始的展东,要注意
mLinearLayout.getChildAt(oldPosition).setEnabled(false);
mLinearLayout.getChildAt(currentIndex-1).setEnabled(true);
oldPosition = currentIndex-1 ;
Log.e("wenzhihao","position=="+position+",currentIndex="+currentIndex);
}
@Override
public void onPageScrollStateChanged(int state) {
if(state==ViewPager.SCROLL_STATE_IDLE){
viewPager.setCurrentItem(currentIndex,false);
play();
}else if(state==ViewPager.SCROLL_STATE_DRAGGING){
cancel();
}
}
});
setIndicatorDot();
mLinearLayout.getChildAt(0).setEnabled(true);
}
/**
* 播放,根據(jù)autoplay
*/
public void play(){
if (autoPlay){
handler.postDelayed(runnable,time);
}else {
handler.removeCallbacks(runnable);
}
}
/**
* 取消播放
*/
public void cancel(){
handler.removeCallbacks(runnable);
}
/**
* 設(shè)置小圓點(diǎn)
*/
private void setIndicatorDot() {
for (int i = 0;i<mAdapter.getCount()-2;i++){
//添加底部灰點(diǎn)
View v = new View(mContext);
v.setBackgroundResource(R.drawable.bg_dot);
v.setEnabled(false);
//指定其大小
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(20,20);
if (i != 0)
params.leftMargin = 20;
params.bottomMargin = 20;
v.setLayoutParams(params);
mLinearLayout.addView(v);
}
}
/**
* 設(shè)置適配器
* @param adpter
*/
public void setAdapter(T adpter){
mAdapter = adpter ;
viewPager.setAdapter(mAdapter);
initViewPager();
}
/**
* 設(shè)置是否自動(dòng)播放
* @param autoPlay
*/
public void setAutoPlay(boolean autoPlay) {
AutoScrollViewPager.autoPlay = autoPlay;
if (!autoPlay){
handler.removeCallbacks(runnable);
}
}
}
注意主要幾點(diǎn)
- 組合控件炒俱,一個(gè)FrameLayout布局包含ViewPager和一個(gè)小圓點(diǎn)指示器琅锻。
- 自動(dòng)循環(huán)用handler實(shí)現(xiàn),循環(huán)發(fā)送消息向胡。
- 這里需要注意的是setAdapter( )方法恼蓬,只要正常寫PageAdapter傳入即可;
- 在OnPageChangeListener中,onPageSelected的時(shí)候去處理位置問(wèn)題僵芹,就是圖中所說(shuō)的处硬,從左往右滑動(dòng),position==0的時(shí)候切換到4的位置拇派,當(dāng)從右往左滑動(dòng)的時(shí)候荷辕,positon==5的時(shí)候切換到1的位置。onPageScrollStateChanged狀態(tài)改變的時(shí)候件豌,即停止滑動(dòng)的時(shí)候滑到指定位置疮方,當(dāng)手指拖動(dòng)的時(shí)候需要停止自動(dòng)播放;
- 小圓點(diǎn)指示器茧彤,是一個(gè)線性布局根據(jù)圖片數(shù)量添加原點(diǎn)骡显,原點(diǎn)背景為selector;
- 在屏幕顯示的時(shí)候設(shè)置自動(dòng)播放曾掂,離開(kāi)屏幕時(shí)候停止播放惫谤;
- 如果想顯示3個(gè)page需要在viewpager父容器設(shè)置
android:clipChildren="false"
android:layerType="hardware"
//代碼如下
setLayerType(View.LAYER_TYPE_SOFTWARE, null);
setClipChildren(false);
并且設(shè)置viewPager.setPageMargin(pageMargin);,需要加其他特效可以自定義PageTransformer珠洗。
- setAutoPlay方法可以設(shè)置不自動(dòng)循環(huán) viewPager.setAutoPlay(false);
例子
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:orientation="horizontal"
android:layout_height="match_parent">
<com.wzh.AutoScrollViewPager
android:id="@+id/viewpager"
android:layout_width="match_parent"
android:layout_height="300dp">
</com.wzh.AutoScrollViewPager>
</LinearLayout>
MainActivity.java
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
private AutoScrollViewPager viewPager ;
private ViewPagerAdapter adapter ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (AutoScrollViewPager) findViewById(R.id.viewpager);
adapter = new ViewPagerAdapter(this);
viewPager.setAdapter(adapter);
viewPager.setAutoPlay(true);
}
}
ViewPagerAdapter.java
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
/**
* Created by WZH on 2018/4/14.
*/
public class ViewPagerAdapter extends PagerAdapter {
private String[] resIds = {
//最后一張圖片
"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1523772064849&di=7502440dd81352d3e3d584eb810e0acc&imgtype=0&src=http%3A%2F%2Fimage.tianjimedia.com%2FuploadImages%2F2012%2F265%2F5432CKKPF561_1000x500.jpg",
//正真的5張圖片
"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1523772064850&di=dd3588fdf916fce1527f7b53cc536293&imgtype=0&src=http%3A%2F%2Fimage.tianjimedia.com%2FuploadImages%2F2012%2F088%2F9KF35LBMFO74.jpg",
"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1523772064854&di=165a16c1167b38b067b3c82cb830c347&imgtype=0&src=http%3A%2F%2Fattachments.gfan.com%2Fforum%2Fattachments2%2F201303%2F18%2F110902j0e5zjwj0yutt00j.jpg",
"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1523772064877&di=dac68b830070fb6dbf1a9d71fc6b2772&imgtype=0&src=http%3A%2F%2Fi3.download.fd.pchome.net%2Fg1%2FM00%2F0D%2F18%2FoYYBAFS8sGGIUf9wAAJfpTlwpsgAACPGwFaL6cAAl-9928.jpg",
"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1523772294591&di=9633b23326710637bda3b511c87e0fdb&imgtype=jpg&src=http%3A%2F%2Fimg0.imgtn.bdimg.com%2Fit%2Fu%3D1163084700%2C3470735618%26fm%3D214%26gp%3D0.jpg",
"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1523772064849&di=7502440dd81352d3e3d584eb810e0acc&imgtype=0&src=http%3A%2F%2Fimage.tianjimedia.com%2FuploadImages%2F2012%2F265%2F5432CKKPF561_1000x500.jpg",
//第一張圖片
"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1523772064850&di=dd3588fdf916fce1527f7b53cc536293&imgtype=0&src=http%3A%2F%2Fimage.tianjimedia.com%2FuploadImages%2F2012%2F088%2F9KF35LBMFO74.jpg",
};
private Context context ;
public ViewPagerAdapter(Context context) {
this.context = context ;
}
@Override
public int getCount() {
return resIds.length;
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
View view = View.inflate(context, R.layout.vp_item, null);
ImageView imageView = (ImageView) view.findViewById(R.id.image);
Glide.with(context)
.load(resIds[position])
.into(imageView);
// imageView.setImageResource(resIds[position]);
//添加到容器中
container.addView(view);
return view;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view==object;
}
}
// bg_while.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<size android:width="30dp" android:height="30dp"/>
<!--白色-->
<solid android:color="#ffffff" />
<!--半徑-->
<corners android:radius="10dp" />
</shape>
//bg_gray.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<size android:width="20dp" android:height="20dp"/>
<!--灰色-->
<solid android:color="#88aaaaaa" />
<!--半徑-->
<corners android:radius="10dp" />
</shape>
//bg_dot.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/bg_while" android:state_enabled="true" />
<item android:drawable="@drawable/bg_gray" android:state_enabled="false" />
</selector>
效果圖
最近在整理并復(fù)習(xí)一些Android基礎(chǔ)知識(shí)點(diǎn),有問(wèn)題希望大家夠指出许蓖,謝謝蝴猪。