最近在网上找了一个关于京东网站的源码,链接地址:
京东高仿App下载
发现其中有几个亮点:
一,用动画代替进度条;
二、对Tabhost加载Activity的运用(还在研究)
三、对于Gallery的运用;
四、对ViewPager的运用;
五、对自定义AbScrollView的运用(分有背景和没有背景的,待下一步研究;
六、关于调用二维码(条形码)的扫一扫(应该是关于API的,待继续研究)。
首先来看第一个关于动画的界面:
此画面为布局时的静态图,作者这里没有用进度条,可能是因为不够美观吧,那作者是怎么实现的呢?答案已经说了,是动画,思路非常简单,就是初始化ImageView控件,然后加载xml文件写的动画,然后给动画加一个监听事件,最后将ImageView设为动画,java代码如下:
package com.itau.jingdong.ui;
import android.os.Bundle;
import android.os.Handler;
import android.util.DisplayMetrics;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import com.itau.jingdong.R;
import com.itau.jingdong.config.Constants;
import com.itau.jingdong.ui.base.BaseActivity;
public class SplashActivity extends BaseActivity {
public static final String TAG = SplashActivity.class.getSimpleName();
private ImageView mSplashItem_iv = null;
/*
* (non-Javadoc)
*
* @see com.itau.tmall.ui.base.BaseActivity#findViewById()
*/
@Override
protected void findViewById() {
// TODO Auto-generated method stub
mSplashItem_iv = (ImageView) findViewById(R.id.splash_loading_item);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
Constants.SCREEN_DENSITY = metrics.density;
Constants.SCREEN_HEIGHT = metrics.heightPixels;
Constants.SCREEN_WIDTH = metrics.widthPixels;
mHandler = new Handler(getMainLooper());
findViewById();
initView();
}
/*
* (non-Javadoc)
*
* @see com.itau.jingdong.ui.base.BaseActivity#initView()
*/
@Override
protected void initView() {
// TODO Auto-generated method stub
Animation translate = AnimationUtils.loadAnimation(this,
R.anim.splash_loading);
translate.setAnimationListener(new AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
// TODO Auto-generated method stub
}
@Override
public void onAnimationRepeat(Animation animation) {
// TODO Auto-generated method stub
}
@Override
public void onAnimationEnd(Animation animation) {
// TODO Auto-generated method stub
//启动homeactivty,相当于Intent
openActivity(HomeActivity.class);
overridePendingTransition(R.anim.push_left_in,
R.anim.push_left_out);
SplashActivity.this.finish();
}
});
mSplashItem_iv.setAnimation(translate);
}
}
xml布局的ImageView动画代码如下:
R.anim.splash_loading:
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="1000"
android:fromXDelta="0.0"
android:interpolator="@android:anim/accelerate_decelerate_interpolator"
android:toXDelta="60%p"
android:fillAfter="true" />
android:fromXDelta="0" android:toXDelta="-100%p" 往左边消失
android:fromXDelta="-100%p" android:toXDelta="0" 从左边进
android:fromXDelta="0" android:toXDelta="100%p" 往右边消失
android:fromXDelta="100%p" android:toXDelta="0" 从右边进
fillBefore是指动画结束时画面停留在此动画的第一帧; 默认值为true
fillAfter是指动画结束是画面停留在此动画的最后一帧。默认值为false
Interpolator对象 资源ID 功能作用
AccelerateDecelerateInterpolator @android:anim/accelerate_decelerate_interpolator 先加速再减速
AccelerateInterpolator @android:anim/accelerate_interpolator 加速
AnticipateInterpolator @android:anim/anticipate_interpolator 先回退一小步然后加速前进
AnticipateOvershootInterpolator @android:anim/anticipate_overshoot_interpolator 在上一个基础上超出终点一小步再回到终点
BounceInterpolator @android:anim/bounce_interpolator 最后阶段弹球效果
CycleInterpolator @android:anim/cycle_interpolator 周期运动
DecelerateInterpolator @android:anim/decelerate_interpolator 减速
LinearInterpolator @android:anim/linear_interpolator 匀速
OvershootInterpolator @android:anim/overshoot_interpolator 快速到达终点并超出一小步最后回到终点
R.anim.push_left_in:
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate android:fromXDelta="100%" android:toXDelta="0"
android:duration="600" />
set>
R.anim.push_left_out:
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate android:fromXDelta="0" android:toXDelta="-100%"
android:duration="600" />
set>
android:toXDelta=”60%p”这一句是在右边消失,大家可以多测试几个数据看看效果就明白为什么不是100%p了!
接下来讨论第二个问题:对于Gallery和ViewPager的应用,还是先贴图
首先,每张图片都是可动的,布局结构很简单,
第一个是ViewPager,第二个LinerLayout是ViewPager下面的长条,在ViewPager里面的图片运动时,下面的红色长条表示当前图片,节奏保持一致,第三个和第四个都是Gallery图片可以左右拨动,只是在图层下面多加了文字,首先来看看自定义的ViewPager是怎么回事:
package com.itau.jingdong.widgets.jazzviewpager;
import java.util.HashMap;
import java.util.LinkedHashMap;
import com.itau.jingdong.R;
import com.nineoldandroids.view.ViewHelper;
import android.content.Context;
import android.graphics.Camera;
import android.graphics.Color;
import android.graphics.Matrix;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
public class JazzyViewPager extends ViewPager {
public static final String TAG = "JazzyViewPager";
private boolean mEnabled = true;
private boolean mFadeEnabled = false;
private boolean mOutlineEnabled = false;
public static int sOutlineColor = Color.WHITE;
private TransitionEffect mEffect = TransitionEffect.Standard;
private HashMap mObjs = new LinkedHashMap();
private static final float SCALE_MAX = 0.5f;
private static final float ZOOM_MAX = 0.5f;
private static final float ROT_MAX = 15.0f;
public enum TransitionEffect {
Standard, Tablet, CubeIn, CubeOut, FlipVertical, FlipHorizontal, Stack, ZoomIn, ZoomOut, RotateUp, RotateDown, Accordion
//这些都是代表当前的图片是那张
}
public JazzyViewPager(Context context) {
this(context, null);
}
@SuppressWarnings("incomplete-switch")
public JazzyViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
setClipChildren(false);//是否限制子View在其范围内
// TypedArray ta = context.obtainStyledAttributes(attrs,
// R.styleable.JazzyViewPager);
// int effect = ta.getInt(R.styleable.JazzyViewPager_style, 0);
String[] transitions = getResources().getStringArray(
R.array.jazzy_effects);
int effect = 0;
setTransitionEffect(TransitionEffect.valueOf(transitions[0]));
setFadeEnabled(
false);
setOutlineEnabled( false);
setOutlineColor(
Color.WHITE);
// Log.i("tarena", "0-->"+effect+"11"+transitions.length+","+
// ta.getBoolean(R.styleable.JazzyViewPager_fadeEnabled,false)+","+
// ta.getBoolean(R.styleable.JazzyViewPager_outlineEnabled, false)+","+
// ta.getColor(R.styleable.JazzyViewPager_outlineColor,Color.WHITE)+"");
switch (mEffect) {
case Stack:
case ZoomOut:
setFadeEnabled(true);
}
// ta.recycle();
}
public void setTransitionEffect(TransitionEffect effect) {
mEffect = effect;
}
public void setPagingEnabled(boolean enabled) {
mEnabled = enabled;
}
public void setFadeEnabled(boolean enabled) {
mFadeEnabled = enabled;
}
public boolean getFadeEnabled() {
return mFadeEnabled;
}
public void setOutlineEnabled(boolean enabled) {
mOutlineEnabled = enabled;
wrapWithOutlines();
}
public void setOutlineColor(int color) {
sOutlineColor = color;
}
private void wrapWithOutlines() {
for (int i = 0; i < getChildCount(); i++) {
View v = getChildAt(i);
if (!(v instanceof OutlineContainer)) {
removeView(v);
super.addView(wrapChild(v), i);
}
}
}
private View wrapChild(View child) {
if (!mOutlineEnabled || child instanceof OutlineContainer)
return child;
OutlineContainer out = new OutlineContainer(getContext());
out.setLayoutParams(generateDefaultLayoutParams());
child.setLayoutParams(new OutlineContainer.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
out.addView(child);
return out;
}
public void addView(View child) {
super.addView(wrapChild(child));
}
public void addView(View child, int index) {
super.addView(wrapChild(child), index);
}
public void addView(View child, LayoutParams params) {
super.addView(wrapChild(child), params);
}
public void addView(View child, int width, int height) {
super.addView(wrapChild(child), width, height);
}
public void addView(View child, int index, LayoutParams params) {
super.addView(wrapChild(child), index, params);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent arg0) {
return mEnabled ? super.onInterceptTouchEvent(arg0) : false;
}
private State mState;
private int oldPage;
private View mLeft;
private View mRight;
private float mRot;
private float mTrans;
private float mScale;
public enum TransitionEffect {
Standard, Tablet, CubeIn, CubeOut, FlipVertical, FlipHorizontal, Stack, ZoomIn, ZoomOut, RotateUp, RotateDown, Accordion
//这些都是代表当前的图片是那张
}
private void logState(View v, String title) {
Log.v(TAG,
title + ": ROT (" + ViewHelper.getRotation(v) + ", "
+ ViewHelper.getRotationX(v) + ", "
+ ViewHelper.getRotationY(v) + "), TRANS ("
+ ViewHelper.getTranslationX(v) + ", "
+ ViewHelper.getTranslationY(v) + "), SCALE ("
+ ViewHelper.getScaleX(v) + ", "
+ ViewHelper.getScaleY(v) + "), ALPHA "
+ ViewHelper.getAlpha(v));
}
protected void animateScroll(int position, float positionOffset) {
if (mState != State.IDLE) {
mRot = (float) (1 - Math.cos(2 * Math.PI * positionOffset)) / 2 * 30.0f;
ViewHelper.setRotationY(this, mState == State.GOING_RIGHT ? mRot
: -mRot);
ViewHelper.setPivotX(this, getMeasuredWidth() * 0.5f);
ViewHelper.setPivotY(this, getMeasuredHeight() * 0.5f);
}
}
protected void animateTablet(View left, View right, float positionOffset) {
if (mState != State.IDLE) {
if (left != null) {
mRot = 30.0f * positionOffset;
mTrans = getOffsetXForRotation(mRot, left.getMeasuredWidth(),
left.getMeasuredHeight());
ViewHelper.setPivotX(left, left.getMeasuredWidth() / 2);
ViewHelper.setPivotY(left, left.getMeasuredHeight() / 2);
ViewHelper.setTranslationX(left, mTrans);
ViewHelper.setRotationY(left, mRot);
logState(left, "Left");
}
if (right != null) {
mRot = -30.0f * (1 - positionOffset);
mTrans = getOffsetXForRotation(mRot, right.getMeasuredWidth(),
right.getMeasuredHeight());
ViewHelper.setPivotX(right, right.getMeasuredWidth() * 0.5f);
ViewHelper.setPivotY(right, right.getMeasuredHeight() * 0.5f);
ViewHelper.setTranslationX(right, mTrans);
ViewHelper.setRotationY(right, mRot);
logState(right, "Right");
}
}
}
private void animateCube(View left, View right, float positionOffset,
boolean in) {
if (mState != State.IDLE) {
if (left != null) {
mRot = (in ? 90.0f : -90.0f) * positionOffset;
ViewHelper.setPivotX(left, left.getMeasuredWidth());
ViewHelper.setPivotY(left, left.getMeasuredHeight() * 0.5f);
ViewHelper.setRotationY(left, mRot);
}
if (right != null) {
mRot = -(in ? 90.0f : -90.0f) * (1 - positionOffset);
ViewHelper.setPivotX(right, 0);
ViewHelper.setPivotY(right, right.getMeasuredHeight() * 0.5f);
ViewHelper.setRotationY(right, mRot);
}
}
}
private void animateAccordion(View left, View right, float positionOffset) {
if (mState != State.IDLE) {
if (left != null) {
ViewHelper.setPivotX(left, left.getMeasuredWidth());
ViewHelper.setPivotY(left, 0);
ViewHelper.setScaleX(left, 1 - positionOffset);
}
if (right != null) {
ViewHelper.setPivotX(right, 0);
ViewHelper.setPivotY(right, 0);
ViewHelper.setScaleX(right, positionOffset);
}
}
}
private void animateZoom(View left, View right, float positionOffset,
boolean in) {
if (mState != State.IDLE) {
if (left != null) {
mScale = in ? ZOOM_MAX + (1 - ZOOM_MAX) * (1 - positionOffset)
: 1 + ZOOM_MAX - ZOOM_MAX * (1 - positionOffset);
ViewHelper.setPivotX(left, left.getMeasuredWidth() * 0.5f);
ViewHelper.setPivotY(left, left.getMeasuredHeight() * 0.5f);
ViewHelper.setScaleX(left, mScale);
ViewHelper.setScaleY(left, mScale);
}
if (right != null) {
mScale = in ? ZOOM_MAX + (1 - ZOOM_MAX) * positionOffset : 1
+ ZOOM_MAX - ZOOM_MAX * positionOffset;
ViewHelper.setPivotX(right, right.getMeasuredWidth() * 0.5f);
ViewHelper.setPivotY(right, right.getMeasuredHeight() * 0.5f);
ViewHelper.setScaleX(right, mScale);
ViewHelper.setScaleY(right, mScale);
}
}
}
private void animateRotate(View left, View right, float positionOffset,
boolean up) {
if (mState != State.IDLE) {
if (left != null) {
mRot = (up ? 1 : -1) * (ROT_MAX * positionOffset);
mTrans = (up ? -1 : 1)
* (float) (getMeasuredHeight() - getMeasuredHeight()
* Math.cos(mRot * Math.PI / 180.0f));
ViewHelper.setPivotX(left, left.getMeasuredWidth() * 0.5f);
ViewHelper.setPivotY(left, up ? 0 : left.getMeasuredHeight());
ViewHelper.setTranslationY(left, mTrans);
ViewHelper.setRotation(left, mRot);
}
if (right != null) {
mRot = (up ? 1 : -1) * (-ROT_MAX + ROT_MAX * positionOffset);
mTrans = (up ? -1 : 1)
* (float) (getMeasuredHeight() - getMeasuredHeight()
* Math.cos(mRot * Math.PI / 180.0f));
ViewHelper.setPivotX(right, right.getMeasuredWidth() * 0.5f);
ViewHelper.setPivotY(right, up ? 0 : right.getMeasuredHeight());
ViewHelper.setTranslationY(right, mTrans);
ViewHelper.setRotation(right, mRot);
}
}
}
private void animateFlipHorizontal(View left, View right,
float positionOffset, int positionOffsetPixels) {
if (mState != State.IDLE) {
if (left != null) {
mRot = 180.0f * positionOffset;
if (mRot > 90.0f) {
left.setVisibility(View.INVISIBLE);
} else {
if (left.getVisibility() == View.INVISIBLE)
left.setVisibility(View.VISIBLE);
mTrans = positionOffsetPixels;
ViewHelper.setPivotX(left, left.getMeasuredWidth() * 0.5f);
ViewHelper.setPivotY(left, left.getMeasuredHeight() * 0.5f);
ViewHelper.setTranslationX(left, mTrans);
ViewHelper.setRotationY(left, mRot);
}
}
if (right != null) {
mRot = -180.0f * (1 - positionOffset);
if (mRot < -90.0f) {
right.setVisibility(View.INVISIBLE);
} else {
if (right.getVisibility() == View.INVISIBLE)
right.setVisibility(View.VISIBLE);
mTrans = -getWidth() - getPageMargin()
+ positionOffsetPixels;
ViewHelper
.setPivotX(right, right.getMeasuredWidth() * 0.5f);
ViewHelper.setPivotY(right,
right.getMeasuredHeight() * 0.5f);
ViewHelper.setTranslationX(right, mTrans);
ViewHelper.setRotationY(right, mRot);
}
}
}
}
private void animateFlipVertical(View left, View right,
float positionOffset, int positionOffsetPixels) {
if (mState != State.IDLE) {
if (left != null) {
mRot = 180.0f * positionOffset;
if (mRot > 90.0f) {
left.setVisibility(View.INVISIBLE);
} else {
if (left.getVisibility() == View.INVISIBLE)
left.setVisibility(View.VISIBLE);
mTrans = positionOffsetPixels;
ViewHelper.setPivotX(left, left.getMeasuredWidth() * 0.5f);
ViewHelper.setPivotY(left, left.getMeasuredHeight() * 0.5f);
ViewHelper.setTranslationX(left, mTrans);
ViewHelper.setRotationX(left, mRot);
}
}
if (right != null) {
mRot = -180.0f * (1 - positionOffset);
if (mRot < -90.0f) {
right.setVisibility(View.INVISIBLE);
} else {
if (right.getVisibility() == View.INVISIBLE)
right.setVisibility(View.VISIBLE);
mTrans = -getWidth() - getPageMargin()
+ positionOffsetPixels;
ViewHelper
.setPivotX(right, right.getMeasuredWidth() * 0.5f);
ViewHelper.setPivotY(right,
right.getMeasuredHeight() * 0.5f);
ViewHelper.setTranslationX(right, mTrans);
ViewHelper.setRotationX(right, mRot);
}
}
}
}
protected void animateStack(View left, View right, float positionOffset,
int positionOffsetPixels) {
if (mState != State.IDLE) {
if (right != null) {
mScale = (1 - SCALE_MAX) * positionOffset + SCALE_MAX;
mTrans = -getWidth() - getPageMargin() + positionOffsetPixels;
ViewHelper.setScaleX(right, mScale);
ViewHelper.setScaleY(right, mScale);
ViewHelper.setTranslationX(right, mTrans);
}
if (left != null) {
left.bringToFront();
}
}
}
private Matrix mMatrix = new Matrix();
private Camera mCamera = new Camera();
private float[] mTempFloat2 = new float[2];
protected float getOffsetXForRotation(float degrees, int width, int height) {
mMatrix.reset();
mCamera.save();
mCamera.rotateY(Math.abs(degrees));
mCamera.getMatrix(mMatrix);
mCamera.restore();
mMatrix.preTranslate(-width * 0.5f, -height * 0.5f);
mMatrix.postTranslate(width * 0.5f, height * 0.5f);
mTempFloat2[0] = width;
mTempFloat2[1] = height;
mMatrix.mapPoints(mTempFloat2);
return (width - mTempFloat2[0]) * (degrees > 0.0f ? 1.0f : -1.0f);
}
protected void animateFade(View left, View right, float positionOffset) {
if (left != null) {
ViewHelper.setAlpha(left, 1 - positionOffset);
}
if (right != null) {
ViewHelper.setAlpha(right, positionOffset);
}
}
protected void animateOutline(View left, View right) {
if (!(left instanceof OutlineContainer))
return;
if (mState != State.IDLE) {
if (left != null) {
((OutlineContainer) left).setOutlineAlpha(1.0f);
}
if (right != null) {
((OutlineContainer) right).setOutlineAlpha(1.0f);
}
} else {
if (left != null)
((OutlineContainer) left).start();
if (right != null)
((OutlineContainer) right).start();
}
}
@Override
public void onPageScrolled(int position, float positionOffset,
int positionOffsetPixels) {
if (mState == State.IDLE && positionOffset > 0) {
oldPage = getCurrentItem();
mState = position == oldPage ? State.GOING_RIGHT : State.GOING_LEFT;
}
boolean goingRight = position == oldPage;
if (mState == State.GOING_RIGHT && !goingRight)
mState = State.GOING_LEFT;
else if (mState == State.GOING_LEFT && goingRight)
mState = State.GOING_RIGHT;
float effectOffset = isSmall(positionOffset) ? 0 : positionOffset;
// mLeft = getChildAt(position);
// mRight = getChildAt(position+1);
mLeft = findViewFromObject(position);
mRight = findViewFromObject(position + 1);
if (mFadeEnabled)
animateFade(mLeft, mRight, effectOffset);
if (mOutlineEnabled)
animateOutline(mLeft, mRight);
switch (mEffect) {
case Standard:
break;
case Tablet:
animateTablet(mLeft, mRight, effectOffset);
break;
case CubeIn:
animateCube(mLeft, mRight, effectOffset, true);
break;
case CubeOut:
animateCube(mLeft, mRight, effectOffset, false);
break;
case FlipVertical:
animateFlipVertical(mLeft, mRight, positionOffset,
positionOffsetPixels);
break;
case FlipHorizontal:
animateFlipHorizontal(mLeft, mRight, effectOffset,
positionOffsetPixels);
case Stack:
animateStack(mLeft, mRight, effectOffset, positionOffsetPixels);
break;
case ZoomIn:
animateZoom(mLeft, mRight, effectOffset, true);
break;
case ZoomOut:
animateZoom(mLeft, mRight, effectOffset, false);
break;
case RotateUp:
animateRotate(mLeft, mRight, effectOffset, true);
break;
case RotateDown:
animateRotate(mLeft, mRight, effectOffset, false);
break;
case Accordion:
animateAccordion(mLeft, mRight, effectOffset);
break;
}
super.onPageScrolled(position, positionOffset, positionOffsetPixels);
if (effectOffset == 0) {
mState = State.IDLE;
}
}
private boolean isSmall(float positionOffset) {
return Math.abs(positionOffset) < 0.0001;
}
public void setObjectForPosition(Object obj, int position) {
mObjs.put(Integer.valueOf(position), obj);
}
public View findViewFromObject(int position) {
Object o = mObjs.get(Integer.valueOf(position));
if (o == null) {
return null;
}
PagerAdapter a = getAdapter();
View v;
for (int i = 0; i < getChildCount(); i++) {
v = getChildAt(i);
if (a.isViewFromObject(v, o))
return v;
}
return null;
}
}
R.array.jazzy_effects的资源文件:
<string-array name="jazzy_effects">
<item>Standarditem>
<item>Tabletitem>
<item>CubeInitem>
<item>CubeOutitem>
<item>FlipVerticalitem>
<item>FlipHorizontalitem>
<item>Stackitem>
<item>ZoomInitem>
<item>ZoomOutitem>
<item>RotateUpitem>
<item>RotateDownitem>
<item>Accordionitem>
string-array>
现在开始初始化ViewPager:
mHandler = new Handler(getMainLooper())
{
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case 1:
int index = mViewPager.getCurrentItem();
if (index == mImageUrls.size() - 1) {
index = -1;
}
mViewPager.setCurrentItem(index + 1);
mHandler.sendEmptyMessageDelayed(1,
3000);
}
}
};
该mHandler是继承自父类Handler,并且父类并未初始化它,只是做了一个声明,所以我们在onCreate()方法里初始化。但是如果不引用父类的handler的话,ViewPager每次在更换图片的时候就会报错,关于handler没有调用主线程的Looper或者没有调用Looper.parer()等。如果大家今后发现原因请与我分享,谢谢!
接着我们初始化数据了,就是说你准备在ViewPager里面加载几张照片:
mImageUrl = "drawable://" + R.drawable.image01;
mImageUrls.add(mImageUrl);
mImageUrl = "drawable://" + R.drawable.image02;
mImageUrls.add(mImageUrl);
mImageUrl = "drawable://" + R.drawable.image03;
mImageUrls.add(mImageUrl);
mImageUrl = "drawable://" + R.drawable.image04;
mImageUrls.add(mImageUrl);
这里要记住,我们在ViewPager里面限定了最多是十二张,所以如果你需要加载的图片超过这个数的话,这里也需要做更改——
public enum TransitionEffect {
Standard, Tablet, CubeIn, CubeOut, FlipVertical, FlipHorizontal, Stack, ZoomIn, ZoomOut, RotateUp, RotateDown, Accordion
//这些都是代表当前的图片是那张
}
接下来继续初始化ViewPager
mViewPager = (JazzyViewPager)findViewById(R.id.jazzviewpager);
mIndicator = (LinearLayout) findViewById(R.id.index_LinearLayout);
mIndicators = new ImageView[mImageUrls.size()];
if (mImageUrls.size() <= 1) {
mIndicator.setVisibility(View.GONE);
}
for (int i = 0; i < mIndicators.length; i++) {
ImageView imageView = new ImageView(this);
LayoutParams params = new LayoutParams(0,
LayoutParams.WRAP_CONTENT, 1.0f);
if (i != 0) {
params.leftMargin = 5;
}
imageView.setLayoutParams(params);
mIndicators[i] = imageView;
if (i == 0) {
mIndicators[i]
.setBackgroundResource(R.drawable.android_activities_cur);
} else {
mIndicators[i]
.setBackgroundResource(R.drawable.android_activities_bg);
}
mIndicator.addView(imageView);
}
mImageViews = new ImageView[mImageUrls.size()];
for (int i = 0; i < mImageViews.length; i++) {
ImageView imageView = new ImageView(this);
imageView.setScaleType(ScaleType.CENTER_CROP);
mImageViews[i] = imageView;
}
mViewPager.setTransitionEffect(TransitionEffect.CubeOut);
mViewPager.setCurrentItem(0);
mHandler.sendEmptyMessageDelayed(1, 3000);
mViewPager.setAdapter(new MyAdapter());
mViewPager.setOnPageChangeListener(new MyPageChangeListener());
mViewPager.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
if (mImageUrls.size() == 0 || mImageUrls.size() == 1)
return true;
else
return false;
}
});
/**
* 当ViewPager中页面的状态发生改变时调用
*
* @author Administrator
*
*/
private class MyPageChangeListener implements OnPageChangeListener {
/**
* This method will be invoked when a new page becomes selected.
* position: Position index of the new selected page.
*/
public void onPageSelected(int position) {
setImageBackground(position);
}
public void onPageScrollStateChanged(int arg0) {
}
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
}
/**
* 设置选中的tip的背景
*
* @param selectItemsIndex
*/
private void setImageBackground(int selectItemsIndex) {
for (int i = 0; i < mIndicators.length; i++) {
if (i == selectItemsIndex) {
mIndicators[i]
.setBackgroundResource(R.drawable.android_activities_cur);
} else {
mIndicators[i]
.setBackgroundResource(R.drawable.android_activities_bg);
}
}
}
public class MyAdapter extends PagerAdapter {
@Override
public int getCount() {
return mImageViews.length;
}
@Override
public boolean isViewFromObject(View view, Object obj) {
if (view instanceof OutlineContainer) {
return ((OutlineContainer) view).getChildAt(0) == obj;
} else {
return view == obj;
}
}
@Override
public void destroyItem(View container, int position, Object object) {
((ViewPager) container).removeView(mViewPager
.findViewFromObject(position));
}
@Override
public Object instantiateItem(View container, int position) {
ImageLoader.getInstance().displayImage(mImageUrls.get(position),
mImageViews[position]);
((ViewPager) container).addView(mImageViews[position], 0);
mViewPager.setObjectForPosition(mImageViews[position], position);
return mImageViews[position];
}
}
现在ViewPager就初始化好了,接着我们来看看这个Gallery
首先一样的准备好数据,
mItemData = new IndexGalleryItemData();
mItemData.setId(1);
mItemData.setImageUrl("drawable://" + R.drawable.index_gallery_01);
mItemData.setPrice("¥79.00");
mStormListData.add(mItemData);
mItemData = new IndexGalleryItemData();
mItemData.setId(2);
mItemData.setImageUrl("drawable://" + R.drawable.index_gallery_02);
mItemData.setPrice("¥89.00");
mStormListData.add(mItemData);
mItemData = new IndexGalleryItemData();
mItemData.setId(3);
mItemData.setImageUrl("drawable://" + R.drawable.index_gallery_03);
mItemData.setPrice("¥99.00");
mStormListData.add(mItemData);
mItemData = new IndexGalleryItemData();
mItemData.setId(4);
mItemData.setImageUrl("drawable://" + R.drawable.index_gallery_04);
mItemData.setPrice("¥109.00");
mStormListData.add(mItemData);
mItemData = new IndexGalleryItemData();
mItemData.setId(5);
mItemData.setImageUrl("drawable://" + R.drawable.index_gallery_05);
mItemData.setPrice("¥119.00");
mStormListData.add(mItemData);
mItemData = new IndexGalleryItemData();
mItemData.setId(6);
mItemData.setImageUrl("drawable://" + R.drawable.index_gallery_06);
mItemData.setPrice("¥129.00");
mStormListData.add(mItemData);
mItemData = new IndexGalleryItemData();
mItemData.setId(7);
mItemData.setImageUrl("drawable://" + R.drawable.index_gallery_07);
mItemData.setPrice("¥139.00");
mStormListData.add(mItemData);
mItemData = new IndexGalleryItemData();
mItemData.setId(8);
mItemData.setImageUrl("drawable://" + R.drawable.index_gallery_08);
mItemData.setPrice("¥69.00");
mPromotionListData.add(mItemData);
mItemData = new IndexGalleryItemData();
mItemData.setId(9);
mItemData.setImageUrl("drawable://" + R.drawable.index_gallery_09);
mItemData.setPrice("¥99.00");
mPromotionListData.add(mItemData);
mItemData = new IndexGalleryItemData();
mItemData.setId(10);
mItemData.setImageUrl("drawable://" + R.drawable.index_gallery_10);
mItemData.setPrice("¥109.00");
mPromotionListData.add(mItemData);
mItemData = new IndexGalleryItemData();
mItemData.setId(11);
mItemData.setImageUrl("drawable://" + R.drawable.index_gallery_11);
mItemData.setPrice("¥119.00");
mPromotionListData.add(mItemData);
mItemData = new IndexGalleryItemData();
mItemData.setId(12);
mItemData.setImageUrl("drawable://" + R.drawable.index_gallery_12);
mItemData.setPrice("¥129.00");
mPromotionListData.add(mItemData);
mItemData = new IndexGalleryItemData();
mItemData.setId(13);
mItemData.setImageUrl("drawable://" + R.drawable.index_gallery_13);
mItemData.setPrice("¥139.00");
mPromotionListData.add(mItemData);
mItemData = new IndexGalleryItemData();
mItemData.setId(14);
mItemData.setImageUrl("drawable://" + R.drawable.index_gallery_14);
mItemData.setPrice("¥149.00");
mPromotionListData.add(mItemData);
然后初始化控件:
mStormGallery = (Gallery) findViewById(R.id.index_testA_gallery);
mPromotionGallery = (Gallery) findViewById(R.id.index_testB_gallery);
然后设置Adapter:
mStormAdapter = new IndexGalleryAdapter(this,
R.layout.activity_index_gallery_item, mStormListData,
new int[] { R.id.index_gallery_item_image,
R.id.index_gallery_item_text });
mStormGallery.setAdapter(mStormAdapter);
mPromotionAdapter = new IndexGalleryAdapter(this,
R.layout.activity_index_gallery_item, mPromotionListData,
new int[] { R.id.index_gallery_item_image,
R.id.index_gallery_item_text });
mPromotionGallery.setAdapter(mPromotionAdapter);
mStormGallery.setSelection(3);
mPromotionGallery.setSelection(3);
这个Adapter也是自定义的,
package com.itau.jingdong.adapter;
import java.util.List;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.itau.jingdong.entity.IndexGalleryItemData;
import com.nostra13.universalimageloader.core.ImageLoader;
public class IndexGalleryAdapter extends BaseAdapter {
Context context;
int layoutId;
int to[];
List listData;
public IndexGalleryAdapter(Context context, int layoutId,
List listData, int to[]) {
this.context = context;
this.layoutId = layoutId;
this.listData = listData;
this.to = to;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return listData.size() == 0 ? 0 : listData.size();
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return listData.get(position);
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder viewHolder;
final int pos = position;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(layoutId, parent, false);
viewHolder = new ViewHolder();
viewHolder.imageView = (ImageView) convertView.findViewById(to[0]);
viewHolder.textView = (TextView) convertView.findViewById(to[1]);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
resetViewHolder(viewHolder);
}
ImageLoader.getInstance().displayImage(listData.get(pos).getImageUrl(),
viewHolder.imageView);
viewHolder.textView.setText(listData.get(pos).getPrice());
return convertView;
}
static class ViewHolder {
ImageView imageView;
TextView textView;
}
protected void resetViewHolder(ViewHolder viewHolder) {
viewHolder.imageView.setImageBitmap(null);
viewHolder.textView.setText("");
}
}
后这样就可以实现我们要的效果了!
关于ViewPager里面图片自动播放的时候动画可以自己在自定义ViewPager里面更改
最后贴上java全部代码:
package com.itau.jingdong;
import java.util.ArrayList;
import java.util.List;
import com.itau.jingdong.adapter.IndexGalleryAdapter;
import com.itau.jingdong.entity.IndexGalleryItemData;
import com.itau.jingdong.ui.base.BaseActivity;
import com.itau.jingdong.widgets.jazzviewpager.JazzyViewPager;
import com.itau.jingdong.widgets.jazzviewpager.JazzyViewPager.TransitionEffect;
import com.itau.jingdong.widgets.jazzviewpager.OutlineContainer;
import com.nostra13.universalimageloader.core.ImageLoader;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
public class TestActivity extends BaseActivity {
private JazzyViewPager mViewPager;
private LinearLayout mIndicator;
private List mImageUrls = new ArrayList();
private String mImageUrl = null;
/**
* 装指引的ImageView数组
*/
private ImageView[] mIndicators;
/**
* 装ViewPager中ImageView的数组
*/
private ImageView[] mImageViews;
// ============== 广告切换 ===================
private Gallery mStormGallery = null;
private Gallery mPromotionGallery = null;
private IndexGalleryAdapter mStormAdapter = null;
private IndexGalleryAdapter mPromotionAdapter = null;
private List mStormListData = new ArrayList();
private List mPromotionListData = new ArrayList();
private IndexGalleryItemData mItemData = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
mHandler = new Handler(getMainLooper())
{
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case 1:
int index = mViewPager.getCurrentItem();
if (index == mImageUrls.size() - 1) {
index = -1;
}
mViewPager.setCurrentItem(index + 1);
mHandler.sendEmptyMessageDelayed(1,
3000);
}
}
};
initData();
mViewPager = (JazzyViewPager)findViewById(R.id.jazzviewpager);
mIndicator = (LinearLayout) findViewById(R.id.index_LinearLayout);
mStormGallery = (Gallery) findViewById(R.id.index_testA_gallery);
mPromotionGallery = (Gallery) findViewById(R.id.index_testB_gallery);
mIndicators = new ImageView[mImageUrls.size()];
if (mImageUrls.size() <= 1) {
mIndicator.setVisibility(View.GONE);
}
for (int i = 0; i < mIndicators.length; i++) {
ImageView imageView = new ImageView(this);
LayoutParams params = new LayoutParams(0,
LayoutParams.WRAP_CONTENT, 1.0f);
if (i != 0) {
params.leftMargin = 5;
}
imageView.setLayoutParams(params);
mIndicators[i] = imageView;
if (i == 0) {
mIndicators[i]
.setBackgroundResource(R.drawable.android_activities_cur);
} else {
mIndicators[i]
.setBackgroundResource(R.drawable.android_activities_bg);
}
mIndicator.addView(imageView);
}
mImageViews = new ImageView[mImageUrls.size()];
for (int i = 0; i < mImageViews.length; i++) {
ImageView imageView = new ImageView(this);
imageView.setScaleType(ScaleType.CENTER_CROP);
mImageViews[i] = imageView;
}
mViewPager.setTransitionEffect(TransitionEffect.CubeOut);
mViewPager.setCurrentItem(0);
mHandler.sendEmptyMessageDelayed(1, 3000);
mViewPager.setAdapter(new MyAdapter());
mViewPager.setOnPageChangeListener(new MyPageChangeListener());
mViewPager.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
if (mImageUrls.size() == 0 || mImageUrls.size() == 1)
return true;
else
return false;
}
});
mStormAdapter = new IndexGalleryAdapter(this,
R.layout.activity_index_gallery_item, mStormListData,
new int[] { R.id.index_gallery_item_image,
R.id.index_gallery_item_text });
mStormGallery.setAdapter(mStormAdapter);
mPromotionAdapter = new IndexGalleryAdapter(this,
R.layout.activity_index_gallery_item, mPromotionListData,
new int[] { R.id.index_gallery_item_image,
R.id.index_gallery_item_text });
mPromotionGallery.setAdapter(mPromotionAdapter);
mStormGallery.setSelection(3);
mPromotionGallery.setSelection(3);
}
private void initData() {
mImageUrl = "drawable://" + R.drawable.image01;
mImageUrls.add(mImageUrl);
mImageUrl = "drawable://" + R.drawable.image02;
mImageUrls.add(mImageUrl);
mImageUrl = "drawable://" + R.drawable.image03;
mImageUrls.add(mImageUrl);
mImageUrl = "drawable://" + R.drawable.image04;
mImageUrls.add(mImageUrl);
// mImageUrl = "drawable://" + R.drawable.image05;
// mImageUrls.add(mImageUrl);
//
// mImageUrl = "drawable://" + R.drawable.image06;
// mImageUrls.add(mImageUrl);
//
// mImageUrl = "drawable://" + R.drawable.image07;
// mImageUrls.add(mImageUrl);
//
// mImageUrl = "drawable://" + R.drawable.image08;
// mImageUrls.add(mImageUrl);
mItemData = new IndexGalleryItemData();
mItemData.setId(1);
mItemData.setImageUrl("drawable://" + R.drawable.index_gallery_01);
mItemData.setPrice("¥79.00");
mStormListData.add(mItemData);
mItemData = new IndexGalleryItemData();
mItemData.setId(2);
mItemData.setImageUrl("drawable://" + R.drawable.index_gallery_02);
mItemData.setPrice("¥89.00");
mStormListData.add(mItemData);
mItemData = new IndexGalleryItemData();
mItemData.setId(3);
mItemData.setImageUrl("drawable://" + R.drawable.index_gallery_03);
mItemData.setPrice("¥99.00");
mStormListData.add(mItemData);
mItemData = new IndexGalleryItemData();
mItemData.setId(4);
mItemData.setImageUrl("drawable://" + R.drawable.index_gallery_04);
mItemData.setPrice("¥109.00");
mStormListData.add(mItemData);
mItemData = new IndexGalleryItemData();
mItemData.setId(5);
mItemData.setImageUrl("drawable://" + R.drawable.index_gallery_05);
mItemData.setPrice("¥119.00");
mStormListData.add(mItemData);
mItemData = new IndexGalleryItemData();
mItemData.setId(6);
mItemData.setImageUrl("drawable://" + R.drawable.index_gallery_06);
mItemData.setPrice("¥129.00");
mStormListData.add(mItemData);
mItemData = new IndexGalleryItemData();
mItemData.setId(7);
mItemData.setImageUrl("drawable://" + R.drawable.index_gallery_07);
mItemData.setPrice("¥139.00");
mStormListData.add(mItemData);
mItemData = new IndexGalleryItemData();
mItemData.setId(8);
mItemData.setImageUrl("drawable://" + R.drawable.index_gallery_08);
mItemData.setPrice("¥69.00");
mPromotionListData.add(mItemData);
mItemData = new IndexGalleryItemData();
mItemData.setId(9);
mItemData.setImageUrl("drawable://" + R.drawable.index_gallery_09);
mItemData.setPrice("¥99.00");
mPromotionListData.add(mItemData);
mItemData = new IndexGalleryItemData();
mItemData.setId(10);
mItemData.setImageUrl("drawable://" + R.drawable.index_gallery_10);
mItemData.setPrice("¥109.00");
mPromotionListData.add(mItemData);
mItemData = new IndexGalleryItemData();
mItemData.setId(11);
mItemData.setImageUrl("drawable://" + R.drawable.index_gallery_11);
mItemData.setPrice("¥119.00");
mPromotionListData.add(mItemData);
mItemData = new IndexGalleryItemData();
mItemData.setId(12);
mItemData.setImageUrl("drawable://" + R.drawable.index_gallery_12);
mItemData.setPrice("¥129.00");
mPromotionListData.add(mItemData);
mItemData = new IndexGalleryItemData();
mItemData.setId(13);
mItemData.setImageUrl("drawable://" + R.drawable.index_gallery_13);
mItemData.setPrice("¥139.00");
mPromotionListData.add(mItemData);
mItemData = new IndexGalleryItemData();
mItemData.setId(14);
mItemData.setImageUrl("drawable://" + R.drawable.index_gallery_14);
mItemData.setPrice("¥149.00");
mPromotionListData.add(mItemData);
}
/**
* 当ViewPager中页面的状态发生改变时调用
*
* @author Administrator
*
*/
private class MyPageChangeListener implements OnPageChangeListener {
/**
* This method will be invoked when a new page becomes selected.
* position: Position index of the new selected page.
*/
public void onPageSelected(int position) {
setImageBackground(position);
}
public void onPageScrollStateChanged(int arg0) {
}
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
}
/**
* 设置选中的tip的背景
*
* @param selectItemsIndex
*/
private void setImageBackground(int selectItemsIndex) {
for (int i = 0; i < mIndicators.length; i++) {
if (i == selectItemsIndex) {
mIndicators[i]
.setBackgroundResource(R.drawable.android_activities_cur);
} else {
mIndicators[i]
.setBackgroundResource(R.drawable.android_activities_bg);
}
}
}
public class MyAdapter extends PagerAdapter {
@Override
public int getCount() {
return mImageViews.length;
}
@Override
public boolean isViewFromObject(View view, Object obj) {
if (view instanceof OutlineContainer) {
return ((OutlineContainer) view).getChildAt(0) == obj;
} else {
return view == obj;
}
}
@Override
public void destroyItem(View container, int position, Object object) {
((ViewPager) container).removeView(mViewPager
.findViewFromObject(position));
}
@Override
public Object instantiateItem(View container, int position) {
ImageLoader.getInstance().displayImage(mImageUrls.get(position),
mImageViews[position]);
((ViewPager) container).addView(mImageViews[position], 0);
mViewPager.setObjectForPosition(mImageViews[position], position);
return mImageViews[position];
}
}
@Override
protected void findViewById() {
// TODO Auto-generated method stub
}
@Override
protected void initView() {
// TODO Auto-generated method stub
}
}
布局文件:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.itau.jingdong.TestActivity" >
<com.itau.jingdong.widgets.jazzviewpager.JazzyViewPager
android:id="@+id/jazzviewpager"
android:layout_width="match_parent"
android:layout_height="300dp"
android:background="@color/white" />
<LinearLayout
android:id="@+id/index_LinearLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/white"
android:orientation="horizontal" />
<Gallery
android:id="@+id/index_testA_gallery"
android:layout_width="match_parent"
android:layout_height="@dimen/index_gallery_height"
android:layout_marginBottom="15dp"
android:spacing="10dp" />
<Gallery
android:id="@+id/index_testB_gallery"
android:layout_width="match_parent"
android:layout_height="@dimen/index_gallery_height"
android:layout_marginBottom="35dp"
android:spacing="10dp" />
LinearLayout>