码迷,mamicode.com
首页 > 其他好文 > 详细

Handler+Timer/TimerTask实现ViewPager的自动循环播放

时间:2016-05-13 00:07:53      阅读:316      评论:0      收藏:0      [点我收藏+]

标签:

ViewPager是android.support.v4中提供的空间,和IOS中的UIScrollView有类似的效果,ViewPager正常工作需要一个PagerAdapter。

PagerAdapter.java如下:

package com.mxd.studyandroid;

import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

public class ViewPagerAdapter extends PagerAdapter
{

	private ImageView[] datas;

	public ViewPagerAdapter(ImageView[] datas)
	{
		this.datas = datas;
	}

	@Override
	public int getCount()
	{
		return datas.length;
	}

	@Override
	public boolean isViewFromObject(View view, Object obj)
	{
		return view == obj;
	}

	@Override
	public void destroyItem(ViewGroup container, int position, Object object)
	{
		container.removeView(datas[position]);
	}

	@Override
	public Object instantiateItem(ViewGroup container, int position)
	{
		container.addView(datas[position], 0);
		return datas[position];
	}
}

在xml文件中引入ViewPager空间:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/btnStop"
        android:layout_width="match_parent"
        android:layout_height="43.0dip"
        android:layout_marginTop="20.0dip"
        android:text="STOP" />

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="200.0dip"
        android:layout_height="200.0dip"
        android:layout_centerInParent="true" />

</RelativeLayout>

1. 使用Handler+Timer+TimerTask实现ViewPager的自动切换:

public class ViewPagerActivity extends Activity
{

	@SuppressLint("HandlerLeak")
	Handler handler = new Handler()
	{
		public void handleMessage(android.os.Message msg)
		{
			if (msg.what == 0x1)
			{
				viewpager.setCurrentItem(index % pagerCount, true);
			}
		};
	};

	ViewPager viewpager;
	Button btnStop;

	int[] imageBgs = new int[]
	{ R.drawable.weather_0, R.drawable.weather_1, R.drawable.weather_2, R.drawable.weather_3, R.drawable.weather_4 };
	ImageView[] imgDatas = new ImageView[imageBgs.length]; // 装载ViewPager中加载的ImageView视图

	Timer pagerTimer = null;
	// index每隔1s自加1,pagerCount为ViewPager中的Pager数量
	int index = 0, pagerCount = imgDatas.length;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_viewpager);

		viewpager = (ViewPager) findViewById(R.id.viewpager);
		// 初始化ViewPager中加载的ImageView
		for (int i = 0, count = imageBgs.length; i < count; i++)
		{
			ImageView img = new ImageView(getApplicationContext());
			img.setScaleType(ImageView.ScaleType.FIT_XY);
			img.setBackgroundResource(imageBgs[i]);
			imgDatas[i] = img;
		}

		ViewPagerAdapter adapter = new ViewPagerAdapter(imgDatas);
		viewpager.setAdapter(adapter);
		viewpager.setCurrentItem(0);
		// viewpager.setCurrentItem(0, true); 是否smoothScroll

		pagerTimer = new Timer(); // 用于循环ViewPager的Timer
		pagerTimer.schedule(new TimerTask()
		{
			@Override
			public void run()
			{
				index++;
				handler.sendEmptyMessage(0x1);
			}
		}, 1000, 2000); // TimerTask, long delay, long period

		btnStop = (Button) findViewById(R.id.btnStop);
		btnStop.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				pagerTimer.cancel();
			}
		});
	}
}

[注意]

此处不能在TimerTask的run()方法中进行 viewPager.setCurrentItem(pagerIndex, true)更新UI的操作,new TimerTask是开启了一个子线程,非UIThread中更新UI回报错。


2.只使用Handler实现ViewPager的自动切换:

public class ViewPagerActivity extends Activity
{

	@SuppressLint("HandlerLeak")
	Handler handler = new Handler();

	ViewPager viewpager;
	Button btnStop;

	int[] imageBgs = new int[]
	{ R.drawable.weather_0, R.drawable.weather_1, R.drawable.weather_2, R.drawable.weather_3, R.drawable.weather_4 };
	ImageView[] imgDatas = new ImageView[imageBgs.length]; // 装载ViewPager中加载的ImageView视图

	// index每隔1s自加1,pagerCount为ViewPager中的Pager数量
	int index = 0, pagerCount = imgDatas.length;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_viewpager);

		viewpager = (ViewPager) findViewById(R.id.viewpager);
		// 初始化ViewPager中加载的ImageView
		for (int i = 0, count = imageBgs.length; i < count; i++)
		{
			ImageView img = new ImageView(getApplicationContext());
			img.setScaleType(ImageView.ScaleType.FIT_XY);
			img.setBackgroundResource(imageBgs[i]);
			imgDatas[i] = img;
		}

		ViewPagerAdapter adapter = new ViewPagerAdapter(imgDatas);
		viewpager.setAdapter(adapter);
		viewpager.setCurrentItem(0);
		// viewpager.setCurrentItem(0, true); 是否smoothScroll

		handler.post(updatePagerRunnable); // 开启ViewPager的循环

		btnStop = (Button) findViewById(R.id.btnStop);
		btnStop.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				handler.removeCallbacks(updatePagerRunnable);
			}
		});
	}

	private Runnable updatePagerRunnable = new Runnable()
	{
		@Override
		public void run()
		{
			index++;
			viewpager.setCurrentItem(index % pagerCount, true);
			handler.postDelayed(updatePagerRunnable, 1000);
		}
	};
}

[注意]

此处可以不用实现Handler中的handlerMessage(Message)方法,因为我们只是使用了Handler内部的Looper自带的MessageQueue,通知UIThread去更新ViewPager的显示。


上面两种方法实现的效果是一样的:

技术分享

Handler+Timer/TimerTask实现ViewPager的自动循环播放

标签:

原文地址:http://blog.csdn.net/tianmaxingkong_/article/details/51344859

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!