[Android Notes] view. getX differs from view. getTranslationX. androidview. getx
1. view. getTranslationX calculates the offset of the view. The initial value is 0, the offset to the left is negative, and the offset to the right is positive.
2. view. getX is equivalent to the distance between the view and the left edge of the parent container, and is equal to getLeft + getTranslationX.:
Example: Layout file:
<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 is 70px to the left of its parent container --/> android: src = "@ drawable/ic_launcher"/> </LinearLayout> </RelativeLayout>
Interface code:
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;@Overrideprotected void onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);iv = (ImageView) findViewById(R.id.iv);iv.setOnClickListener(this);}@Overridepublic void onClick(View v){Log.d(TAG,"translationX:"+iv.getTranslationX()+",x:"+iv.getX());ObjectAnimator.ofFloat(iv,"translationX",-30f).setDuration(1000).start();}}
Click the robot twice to view the log:
It can be found that the first translationX is 0, while the getX value is 70. the second offset is 30 Px to the left, so translationX is-30px, while getX is 70-30 = 40px. This is irrelevant to the margin of the parent container linearLayout!