Java tutorial
//package com.java2s; //License from project: Apache License import android.os.Build; import android.view.View; import android.view.ViewGroup; public class Main { /** * Apply a parallax effect to a View/ViewGroup * @param view A View or ViewGroup * @param recursive Applies if {@code view} is a ViewGroup. If true, this will recursively go through any child ViewGroups and apply the effect to their children. * If false, only {@code view}'s immediate children will move in the parallax effect * @param offsetPixels The current pixel offset for the page {@code view} is on. * @param startParallaxFactor The speed at which the first child should move. Negative values for slower, positive for faster. * @param parallaxInterval The difference in speed between the children. */ public static void applyParallaxEffect(View view, boolean recursive, int offsetPixels, float startParallaxFactor, float parallaxInterval) { if (recursive) applyParallaxEffectRecursively(view, offsetPixels, startParallaxFactor, parallaxInterval, 0); else applyParallaxEffectToImmediateChildren(view, offsetPixels, startParallaxFactor, parallaxInterval); } private static int applyParallaxEffectRecursively(View view, int offsetPixels, float startParallaxFactor, float parallaxInterval, int index) { int nextIndex = index; if (view instanceof ViewGroup) { ViewGroup group = (ViewGroup) view; for (int i = 0; i < group.getChildCount(); i++) { nextIndex = applyParallaxEffectRecursively(group.getChildAt(i), offsetPixels, startParallaxFactor, parallaxInterval, nextIndex); } } else { translateViewForParallaxEffect(view, index, offsetPixels, startParallaxFactor, parallaxInterval); nextIndex++; } return nextIndex; } private static void applyParallaxEffectToImmediateChildren(View view, int offsetPixels, float startParallaxFactor, float parallaxInterval) { if (view instanceof ViewGroup) { ViewGroup group = (ViewGroup) view; for (int i = 0; i < group.getChildCount(); i++) { translateViewForParallaxEffect(group.getChildAt(i), i, offsetPixels, startParallaxFactor, parallaxInterval); } } else { translateViewForParallaxEffect(view, 0, offsetPixels, startParallaxFactor, parallaxInterval); } } private static void translateViewForParallaxEffect(View view, int index, int offsetPixels, float startParallaxFactor, float parallaxInterval) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { view.setTranslationX( calculateParallaxOffsetAmount(index, offsetPixels, startParallaxFactor, parallaxInterval)); } } private static float calculateParallaxOffsetAmount(int index, int offsetPixels, float startParallaxFactor, float parallaxInterval) { return (startParallaxFactor + (index * parallaxInterval)) * -offsetPixels; } }