package com.loaderman.customviewdemo; 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; import android.widget.Toast; public class MainActivity extends AppCompatActivity { private TextView tv; private Button btn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tv = (TextView) findViewById(R.id.tv); btn = (Button) findViewById(R.id.btn); btn.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { doAnimation(); } }); tv.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Toast.makeText(MainActivity.this, "clicked me", Toast.LENGTH_SHORT).show(); } }); } private void doAnimation(){ ValueAnimator animator = ValueAnimator.ofInt(0,400);//从屏幕的左上角(0,0)到屏幕(400,400) animator.setDuration(1000); animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { public void onAnimationUpdate(ValueAnimator animation) { int curValue = (Integer)animation.getAnimatedValue(); tv.layout(curValue,curValue,curValue+tv.getWidth(),curValue+tv.getHeight()); } }); animator.start(); } }
<?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:padding="10dp" android:text="start anim" /> <TextView android:id="@+id/tv" android:layout_width="wrap_content" android:layout_height="wrap_content" android:padding="10dp" android:background="#ffff00" android:text="Hello"/> </LinearLayout>