简体   繁体   English

以编程方式设置的边距设置不会立即应用于视图

[英]Margin set programmatically not applied instantly to the view

I'm creating a ImageView programmatically : 我正在以编程方式创建ImageView:

   LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(50,50);
   lp.setMargins(4,4,4,4);

   ImageView color = new ImageView(this);
   color.setLayoutParams(lp);
   colorPicker.addView(color); //adding view to linearlayout
   Log.i("X", "" + color.getX());
   ...

im trying to retrieve color's x poistion via color.getX() , but for some reason it returns 0 instead of 4 meaning its not taking the margin into account 我试图通过color.getX()检索color's x位置,但是由于某种原因,它返回0而不是4这意味着它没有考虑边距

also after doing some search in the docs i found requestLayout() might solve this, but it doesnt help either 在文档中进行了一些搜索之后,我发现requestLayout()可能会解决此问题,但这对您都没有帮助

public void setMargins (int left, int top, int right, int bottom) public void setMargins(int左,int顶部,int右,int底部)

Sets the margins, in pixels. 设置边距,以像素为单位。 A call to requestLayout() needs to be done so that the new margins are taken into account. 需要完成对requestLayout()的调用,以便考虑新的边距。 Left and right margins may be overriden by requestLayout() depending on layout direction. 根据布局方向,requestLayout()可以覆盖左右边距。

UPDATE UPDATE

if i call color.getX() inside onClick listener it returns 4 as expected 如果我在onClick侦听器中调用color.getX()它将按预期返回4

The width , height , margins , etc. of a View aren't applied inmediately, you need to wait for the UI to be sized and laid out on the screen. 不会立即应用Viewwidthheightmargins等,您需要等待UI大小确定并在屏幕上布局。

getWidth() returns 0 if set by android:layout_width="match_parent" 如果由android设置,则getWidth()返回0:layout_width =“ match_parent”

Try this: 尝试这个:

ViewTreeObserver vto = color.getViewTreeObserver(); 
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() { 
    @Override 
    public void onGlobalLayout() { 
        this.layout.getViewTreeObserver().removeGlobalOnLayoutListener(this); 
        Log.i("X", "" + color.getX());

    } 
});

You will need to make "color" variable final or global to be able to access it inside the listener . 您将需要使“ color”变量为finalglobal ,以便能够在listener访问它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM