view.getX和view.getTranslationX区别

1.view.getTranslationX计算的是该view的偏移量。初始值为0,向左偏移值为负,向右偏移值为正。
2.view.getX相当于该view距离父容器左边缘的距离,等于getLeft+getTranslationX。
示意图:

举例:
布局文件:
[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     xmlns:tools="http://schemas.android.com/tools"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     tools:context="com.example.animdemo2.MainActivity" >  
  6.     <LinearLayout  
  7.         android:layout_width="wrap_content"  
  8.         android:layout_height="wrap_content"  
  9.         android:layout_margin="110px"  
  10.         android:orientation="vertical" >  
  11.      
  12.     <ImageView  
  13.         android:id="@+id/iv"  
  14.         android:layout_width="50dp"  
  15.         android:layout_height="50dp"  
  16.         android:layout_marginLeft="70px"<--ImageView距其父容器左边距离为70px--/>  
  17.         android:src="@drawable/ic_launcher" />  
  18.  </LinearLayout>  
  19. </RelativeLayout>  
界面代码:

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. package com.example.animdemo2;  
  2. import android.animation.ObjectAnimator;  
  3. import android.app.Activity;  
  4. import android.os.Bundle;  
  5. import android.util.Log;  
  6. import android.view.View;  
  7. import android.view.View.OnClickListener;  
  8. import android.widget.ImageView;  
  9. public class MainActivity extends Activity implements OnClickListener  
  10. {  
  11.     private static final String TAG = "MainActivity";  
  12.     private ImageView iv;  
  13.     @Override  
  14.     protected void onCreate(Bundle savedInstanceState)  
  15.     {  
  16.         super.onCreate(savedInstanceState);  
  17.         setContentView(R.layout.activity_main);  
  18.         iv = (ImageView) findViewById(R.id.iv);  
  19.         iv.setOnClickListener(this);  
  20.     }  
  21.     @Override  
  22.     public void onClick(View v)  
  23.     {  
  24.         Log.d(TAG,"translationX:"+iv.getTranslationX()+",x:"+iv.getX());  
  25.         ObjectAnimator.ofFloat(iv,"translationX",-30f).setDuration(1000).start();  
  26.     }  
  27. }  
点击机器人两次,查看日志:



可以发现第一次的translationX是0,而getX的值是70.第二次因为发生了偏移,向左偏移了30px,所以translationX是-30px,而getX的值为70-30=40px。这跟其父容器linearLayout的margin无关!


  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值