藉助Handler,實現ViewPager中頁面的自動切換

在不少電商網頁及app上都有自動切換的商品的推廣快,感受體驗挺不錯的,正好今天學習使用ViewPager,所以也實現了一個功能相似的demo。 java

下面是其中的兩個截圖: android

         

實現一個自動播放功能的ViewPager,要作的主要有如下的幾個部分: app


  • 實現一個ViewPagerAdapter,用於爲ViewPager提供展現內容(例如上面的兩張小貓圖片
public class ViewPagerAdapter extends PagerAdapter {
		private List<View> mData;
		public ViewPagerAdapter(List<View> mData) {
			this.mData = mData;
		}

		@Override
		public int getCount() {
			return mData.size();
		}

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


  • 實現一個OnPageChangeListener,這樣在頁面切換後能夠提示當前頁面所在的位置(例如上圖中,左下角的3個圓點,紅色表示當前頁面
private class ViewPageChangeListener implements OnPageChangeListener {

		@Override
		public void onPageScrollStateChanged(int arg0) {
		}

		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {
		}

		//監聽頁面改變事件來改變viewIndicator中的指示圖片
		@Override
		public void onPageSelected(int arg0) {
			int len = viewIndicator.getChildCount();
			for(int i = 0; i < len; ++i)
				viewIndicator.getChildAt(i).setBackgroundResource(R.drawable.tip_normal);
			viewIndicator.getChildAt(arg0).setBackgroundResource(R.drawable.tip_select);
		}
		
	}


  • 實現一個Handler,用於在必定的時間間隔後修改UI(將當前顯示的圖片切換到下一個)

private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch(msg.what) {
			case 1:
				int totalcount = pagers.size();//autoChangeViewPager.getChildCount();
				int currentItem = autoChangeViewPager.getCurrentItem();
				
				int toItem = currentItem + 1 == totalcount ? 0 : currentItem + 1;
				
				Log.i(TAG, "totalcount: " + totalcount + "   currentItem: " + currentItem + "   toItem: " + toItem);
				
				autoChangeViewPager.setCurrentItem(toItem, true);
				
				//每兩秒鐘發送一個message,用於切換viewPager中的圖片
				this.sendEmptyMessageDelayed(1, 2000);
			}
		}
	};



上面這3段就是主要的代碼,除此以外,還須要在onResume()中發送一個起始message以及在onStop()中中止ViewPager頁面的自動切換等內容。

完整的代碼以下: ide

public class MainActivity extends Activity {
	private static final String TAG = MainActivity.class.getSimpleName();
	private ViewPager autoChangeViewPager;
	
	//用來指示當前顯示圖片所在位置
	private LinearLayout viewIndicator;
	
	//包含要在ViewPager中顯示的圖片
	private List<View> pagers;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		autoChangeViewPager = (ViewPager) findViewById(R.id.autoVP);
		viewIndicator = (LinearLayout) findViewById(R.id.vpindicator);
		
		initAdapter();
		
		//監聽頁面改變事件來改變viewIndicator中的指示圖片
		autoChangeViewPager.setOnPageChangeListener(new ViewPageChangeListener());
		
	}
	
	private void initAdapter() {
		//即將在viewPager中展現的圖片資源
		int[] imgs = {R.drawable.i1, R.drawable.i2, R.drawable.i3};
		
		//init pagers;
		pagers = new ArrayList<View>();
		LinearLayout.LayoutParams img_params = new LayoutParams(
				LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT
				);
		for(int i = 0; i < imgs.length; ++i) {
			ImageView iv = new ImageView(this);
			iv.setBackgroundResource(imgs[i]);
			iv.setLayoutParams(img_params);
			final int index = i;
			iv.setOnClickListener(new OnClickListener() {
				//當viewPager中的圖片被點擊後,跳轉到新的activity
				@Override
				public void onClick(View v) {
					Intent i = new Intent(MainActivity.this, InvokedActivity.class);
					i.putExtra("name", "cat " + index);
					MainActivity.this.startActivity(i);
				}
			});
			pagers.add(iv);
		}
		autoChangeViewPager.setAdapter(new ViewPagerAdapter(pagers));
		
		//init indicator
		LinearLayout.LayoutParams ind_params = new LayoutParams(
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT
				);
		for(int i = 0; i < imgs.length; ++i) {
			ImageView iv = new ImageView(this);
			if(i == 0)
				iv.setBackgroundResource(R.drawable.tip_select);
			else
				iv.setBackgroundResource(R.drawable.tip_normal);
			iv.setLayoutParams(ind_params);
			viewIndicator.addView(iv);
		}
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		//activity啓動兩秒鐘後,發送一個message,用來將viewPager中的圖片切換到下一個
		mHandler.sendEmptyMessageDelayed(1, 2000);
	}
	
	@Override
	protected void onStop() {
		super.onStop();
		//中止viewPager中圖片的自動切換
		mHandler.removeMessages(1);
	}

	public class ViewPagerAdapter extends PagerAdapter {
		private List<View> mData;
		public ViewPagerAdapter(List<View> mData) {
			this.mData = mData;
		}

		@Override
		public int getCount() {
			return mData.size();
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == arg1;
		}
		
		@Override
		public Object instantiateItem(ViewGroup container, int position) {
			View v = mData.get(position);
			container.addView(v);
			return v;
		}
		
		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {
//			super.destroyItem(container, position, object);
			container.removeView(mData.get(position));
		}
		
	}
	
	private class ViewPageChangeListener implements OnPageChangeListener {

		@Override
		public void onPageScrollStateChanged(int arg0) {
		}

		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {
		}

		//監聽頁面改變事件來改變viewIndicator中的指示圖片
		@Override
		public void onPageSelected(int arg0) {
			int len = viewIndicator.getChildCount();
			for(int i = 0; i < len; ++i)
				viewIndicator.getChildAt(i).setBackgroundResource(R.drawable.tip_normal);
			viewIndicator.getChildAt(arg0).setBackgroundResource(R.drawable.tip_select);
		}
		
	}
	
	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch(msg.what) {
			case 1:
				int totalcount = pagers.size();//autoChangeViewPager.getChildCount();
				int currentItem = autoChangeViewPager.getCurrentItem();
				
				int toItem = currentItem + 1 == totalcount ? 0 : currentItem + 1;
				
				Log.i(TAG, "totalcount: " + totalcount + "   currentItem: " + currentItem + "   toItem: " + toItem);
				
				autoChangeViewPager.setCurrentItem(toItem, true);
				
				//每兩秒鐘發送一個message,用於切換viewPager中的圖片
				this.sendEmptyMessageDelayed(1, 2000);
			}
		}
	};
}




佈局文件以下:(上面代碼中的InvokedActivity很是簡單,此處就省略了) 佈局

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <android.support.v4.view.ViewPager
        android:id="@+id/autoVP"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <LinearLayout
        android:id="@+id/vpindicator"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        android:orientation="horizontal" />

</FrameLayout>
相關文章
相關標籤/搜索