1.view.getTranslationX计算的是该view的偏移量。初始值为0,向左偏移值为负,向右偏移值为正。
2.view.getX相当于该view距离父容器左边缘的距离,等于getLeft+getTranslationX。
示意图:
举例:
布局文件:
- <RelativeLayout 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"
- tools:context="com.example.animdemo2.MainActivity" >
- <LinearLayout
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_margin="110px"
- android:orientation="vertical" >
-
- <ImageView
- android:id="@+id/iv"
- android:layout_width="50dp"
- android:layout_height="50dp"
- android:layout_marginLeft="70px"<--ImageView距其父容器左边距离为70px--/>
- android:src="@drawable/ic_launcher" />
- </LinearLayout>
- </RelativeLayout>
界面代码:
- package com.example.animdemo2;
- import android.animation.ObjectAnimator;
- import android.app.Activity;
- import android.os.Bundle;
- import android.util.Log;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.ImageView;
- public class MainActivity extends Activity implements OnClickListener
- {
- private static final String TAG = "MainActivity";
- private ImageView iv;
- @Override
- protected void onCreate(Bundle savedInstanceState)
- {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- iv = (ImageView) findViewById(R.id.iv);
- iv.setOnClickListener(this);
- }
- @Override
- public void onClick(View v)
- {
- Log.d(TAG,"translationX:"+iv.getTranslationX()+",x:"+iv.getX());
- ObjectAnimator.ofFloat(iv,"translationX",-30f).setDuration(1000).start();
- }
- }
点击机器人两次,查看日志:
可以发现第一次的translationX是0,而getX的值是70.第二次因为发生了偏移,向左偏移了30px,所以translationX是-30px,而getX的值为70-30=40px。这跟其父容器linearLayout的margin无关!