android 的Tween動畫並不會改變控件的屬性值,比如以下測試片段:
定義一個從屏幕右邊進入,滾動到屏幕左邊消失的一個TranslateAnimation動畫:
<?xml version="1.0" encoding="utf-8"?> <set xmlns:android="http://schemas.android.com/apk/res/android" android:fillEnabled="true" android:fillAfter="true"> <translate android:duration="7000" android:fromXDelta="100%p" android:toXDelta="-100%"/> </set>
在activity里面設置某個TextView的動畫,並且另起一個線程每隔一秒獲取textView的坐標:
public class Activity1 extends Activity { private TextView textView; private Animation animation; private int location[] = new int[2]; private boolean flags = true; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); animation = AnimationUtils.loadAnimation(this,R.anim.scrollanim); textView = (TextView)findViewById(R.id.textview); textView.setOnClickListener( new TextView.OnClickListener() { @Override public void onClick(View v) { textView.startAnimation(animation); } }); getLocationThread.start(); } private Thread getLocationThread = new Thread(){ @Override public void run() { while(flags){ textView.getLocationOnScreen(location); Log.i("test", location[0] + ""); try { Thread.sleep(1000L); } catch (InterruptedException e) { e.printStackTrace(); } } } }; @Override protected void onDestroy() { flags = false; super.onDestroy(); } }
最后LogCat測試結果如下所示:
可見雖然TextView隨着動畫移動了,但是他的位置屬性並沒有改變。
那么如何獲取隨着動畫改變的坐標?
利用Transformation這個類
代碼如下所示:
private Thread getLocationThread = new Thread(){ @Override public void run() { while(flags){ Transformation transformation = new Transformation(); animation.getTransformation(AnimationUtils.currentAnimationTimeMillis(),transformation); Matrix matrix = transformation.getMatrix(); float[] matrixVals = new float[9]; matrix.getValues(matrixVals); Log.i("test", matrixVals[2] + ""); try { Thread.sleep(1000L); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } };
Matrix是由9個float構成的3X3的矩陣,如下所示:
|cosX -sinX translateX|
|sinx cosX translateY|
|0 0 scale |
cosX sinX表示旋轉角度,按順時針方向算。 scale是縮放比例。
啟動線程后 LogCat如下所示: