package com.loaderman.customviewdemo; import android.animation.Animator; import android.animation.ValueAnimator; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.TextView; public class MainActivity extends AppCompatActivity { private TextView tv; private Button btnStart,btnCancel; private ValueAnimator repeatAnimator; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tv = (TextView) findViewById(R.id.tv); btnStart = (Button) findViewById(R.id.btn); btnCancel = (Button)findViewById(R.id.btn_cancel); btnStart.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { repeatAnimator = doRepeatAnim(); } }); btnCancel.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // repeatAnimator.removeAllListeners(); repeatAnimator.cancel(); } }); } private ValueAnimator doRepeatAnim(){ ValueAnimator animator = ValueAnimator.ofInt(0,400); animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { public void onAnimationUpdate(ValueAnimator animation) { int curValue = (Integer)animation.getAnimatedValue(); tv.layout(tv.getLeft(),curValue,tv.getRight(),curValue+tv.getHeight()); } }); animator.addListener(new Animator.AnimatorListener() { public void onAnimationStart(Animator animation) { } public void onAnimationEnd(Animator animation) { } public void onAnimationCancel(Animator animation) { } public void onAnimationRepeat(Animator animation) { } }); animator.setRepeatMode(ValueAnimator.REVERSE); animator.setRepeatCount(ValueAnimator.INFINITE); animator.setDuration(1000); animator.start(); return animator; } }
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context="com.loaderman.customviewdemo.MainActivity"> <Button android:id="@+id/btn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:padding="10dp" android:text="start anim" /> <Button android:id="@+id/btn_cancel" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:padding="10dp" android:text="cancel anim" /> <TextView android:id="@+id/tv" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:padding="10dp" android:background="#ffff00" android:text="Hello"/> </LinearLayout>