以TextView为例我们看看,先看一下我的xml:
<TextView
android:id="@+id/tv_test"
android:layout_width="200dp"
android:layout_height="50dp"
android:layout_marginLeft="20dp"
android:text="Test"/>
看一下原图:

然后我们调一下setX看看:
tv_test.setX(100);
看一下效果:

再看一下setTranslationX:
tv_test.setTranslationX(100);
看一看效果:

接下来我们看一下setX源码:
/**
* Sets the visual x position of this view, in pixels. This is equivalent to setting the
* {@link #setTranslationX(float) translationX} property to be the difference between
* the x value passed in and the current {@link #getLeft() left} property.
*
* @param x The visual x position of this view, in pixels.
*/
public void setX(float x) {
setTranslationX(x - mLeft);
}
这里mLeft就是marginLeft的值由此可以看出setX与setTranslationX区别在于setX减去了marginLeft的值后的偏移量,setTranslationX是直接设置偏移量。
欢迎关注微信公众号!你的每个赞和在看,都是对我的支持!👍
本文通过一个TextView实例详细解析了Android中视图元素的位置属性setX与setTranslationX的区别。通过源码对比,阐述了两者在视图偏移上的不同实现方式。

1948

被折叠的 条评论
为什么被折叠?



