UpMarqueeTextView-模仿淘宝客户端向上滚动的广告条

UpMarqueeTextView一个简单的向上滚动的类似跑马灯效果,项目中用到的时候是接受到推送过来的消息向上滚动一次,没有做动态的gif效果,所以都是一些纯文字的简单记录。
UpMarqueeTextView通过实现TextView使用Animator动画来实现,所以需要满足3.0以下的版本需要使用nineold-androids来实现效果,其实原理什么很简单看看代码就能了解。

public class UpMarqueeTextView extends TextView implements Animator.AnimatorListener {

    private static final String TAG = "UpMarqueeTextView";

    private static final int ANIMATION_DURATION = 200;
    private float height;
    private AnimatorSet mAnimatorStartSet;
    private AnimatorSet mAnimatorEndSet;
    private String mText;

    public UpMarqueeTextView(Context context) {
        super(context);
    }

    public UpMarqueeTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        Log.w(TAG, "--- onDraw ---");
        height = getHeight();// 确保view的高度
    }

    /**--- 初始化向上脱离屏幕的动画效果 ---*/
    private void initStartAnimation() {
        ObjectAnimator translate = ObjectAnimator.ofFloat(this, "translationY", 0, -height);
        ObjectAnimator alpha = ObjectAnimator.ofFloat(this, "alpha", 1f, 0f);
        mAnimatorStartSet = new AnimatorSet();
        mAnimatorStartSet.play(translate).with(alpha);
        mAnimatorStartSet.setDuration(ANIMATION_DURATION);
        mAnimatorStartSet.addListener(this);
    }

    /**--- 初始化从屏幕下面向上的动画效果 ---*/
    private void initEndAnimation() {
        ObjectAnimator translate = ObjectAnimator.ofFloat(this, "translationY", height, 0);
        ObjectAnimator alpha = ObjectAnimator.ofFloat(this, "alpha", 0f, 1f);
        mAnimatorEndSet = new AnimatorSet();
        mAnimatorEndSet.play(translate).with(alpha);
        mAnimatorEndSet.setDuration(ANIMATION_DURATION);
    }

    /**--- 设置内容 ---**/
    public void setText(String text) {
        if (TextUtils.isEmpty(text)) {
            Log.e(TAG, "--- 请确保text不为空 ---");
            return;
        }
        mText = text;
        if (null == mAnimatorStartSet) {
            initStartAnimation();
        }
        mAnimatorStartSet.start();
    }


    @Override
    public void onAnimationStart(Animator animator) {

    }

    @Override
    public void onAnimationEnd(Animator animator) {
        super.setText(mText);
        if (null == mAnimatorEndSet) {
            initEndAnimation();
        }
        mAnimatorEndSet.start();
    }

    @Override
    public void onAnimationCancel(Animator animator) {

    }

    @Override
    public void onAnimationRepeat(Animator animator) {

    }
}

功能确实很简单,设置下动画代码即可实现了。苍蝇虽小也是肉,项目体验下载地址:
https://github.com/Neacy/UpMarqueerTextView/tree/master

你可能感兴趣的:(android效果)