LayoutParams layoutParams=new LayoutParams(int width, int height);
layoutParams.setMargins(int left, int top, int right, int bottom);
imageView.setLayoutParams(layoutParams);
Use LayoutParams.
如果使用 LinearLayout,则必须导入 android.widget。线性布局。LayoutParams,否则导入正确版本的 LayoutParams 以适应您正在使用的布局,否则将导致 ClassCastException,然后:
LayoutParams layoutParams = new LayoutParams(int width, int height);
layoutParams.setMargins(int left, int top, int right, int bottom);
imageView.setLayoutParams(layoutParams);
注意,你也可以使用 imageView.setLeft (int dim) ,但是这个 WO 不会设置组件的位置,它只会设置组件左边框的位置,其余的将保持在相同的位置。
I found that @Stefan Haustein comes very close to my experience, but not sure 100%. My suggestion is:
setLeft()/setRight()/setBottom()/setTop()有时不工作。
如果你想 临时设置一个位置(例如做动画,不影响层次结构)时,添加并显示了视图,只是 使用 ABC0/setY()代替。(你可能想搜索更多在 difference ABC2 and setX())
And note that X, Y seem to be absolute, and it was supported by AbsoluteLayout which now is deprecated. Thus, you feel X, Y is likely not supported any more. And yes, it is, but only partly. It means if your 如果添加了 view,setX ()、 setY ()将完美地工作; otherwise, 什么时候 you try to 将视图添加到视图组布局中 (e.g FrameLayout, LinearLayout, RelativeLayout), you 必须设置 its LayoutParams with 左边,上边 instead (setX(), setY() in this case won't work sometimes).