ColorChanged ViewPager 【code】

2854 단어
Success! oooowww yeahhhhhh!
	public class MyPagerListener implements ViewPager.OnPageChangeListener {

		private int lastValue = -1;
		private int redColor = Color.parseColor("#e51c23");
		private int blueColor = Color.parseColor("#03a9f4");
		private int greenColor = Color.parseColor("#259b24");

		public MyPagerListener() {
			super();
		}

		@Override
		public void onPageSelected(int position) {
			mViewPager.setCurrentItem(position);
			page_position = position;

			if (position == 1) {
				mViewPager.setBackgroundResource(R.color.color_light_blue);
			} else if (position == 2) {
				mViewPager.setBackgroundResource(R.color.color_red);
			} else if (position == 0) {
				mViewPager.setBackgroundResource(R.color.color_green);
			}
		}

		/* 
		 *
		 * Pager  ,finger Right to Left positionOffset 0 to 1
		 *     positionOffsetPixels --
		 * 
		 * Pager  ,finger Left to Right positionOffset 1 to 0
		 *     positionOffsetPixels ++
		 */
		@Override
		public void onPageScrolled(int position, float positionOffset,
				int positionOffsetPixels) {

			if (positionOffset ==0) {
				return;
			}

			if (lastValue > positionOffsetPixels) {
				// Pager  
				if (position == 0) {
					setPagerBg(blueColor, greenColor, 1-positionOffset);
				} else if (position == 1) {
					// Set like this will be right, but I don't know the reason
					setPagerBg(redColor, blueColor, 1-positionOffset);
				} else if (position == 2) {
					Log.e("Right2", position + "");
					setPagerBg(redColor, blueColor, 1-positionOffset);
				}

			} else if (lastValue < positionOffsetPixels) {
				// Pager  
				if (position == 0) {
					Log.e("Left0", position + "");
					setPagerBg(greenColor, blueColor, positionOffset);
				} else if (position == 1) {
					Log.e("Left1", position + "");
					setPagerBg(blueColor, redColor, positionOffset);
				} else if (position == 2) {
					Log.e("Left2", position + "");
					setPagerBg(blueColor, redColor, positionOffset);
				}
			}
			lastValue = positionOffsetPixels;
		}

		@Override
		public void onPageScrollStateChanged(int position) {

		}

		public void setPagerBg(int color1, int color2, float ratio) {
			mViewPager.setBackgroundColor(blendColors(color1, color2,
					ratio));
		}

		/**
		 * Change color1 to color2 the ratio should increase!
		 */
		private int blendColors(int color1, int color2, float ratio) {
			final float inverseRation = 1f - ratio;
			float r = (Color.red(color2) * ratio)
					+ (Color.red(color1) * inverseRation);
			float g = (Color.green(color2) * ratio)
					+ (Color.green(color1) * inverseRation);
			float b = (Color.blue(color2) * ratio)
					+ (Color.blue(color1) * inverseRation);
			return Color.rgb((int) r, (int) g, (int) b);
		}

	}

좋은 웹페이지 즐겨찾기