2

我正在以编程方式创建 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());
   ...

我试图通过检索color'sx 位置color.getX(),但由于某种原因它返回0而不是4意味着它没有考虑到边距

在我发现的文档中进行一些搜索之后也requestLayout()可以解决这个问题,但它也无济于事

public void setMargins (int left, int top, int right, int bottom)

设置边距,以像素为单位。需要调用 requestLayout() 以便考虑新的边距。requestLayout() 可能会根据布局方向覆盖左右边距。

更新

如果我color.getX()在 onClick 监听器内部调用它会按预期返回 4

4

1 回答 1

3

a的width, height,marginsView不会立即应用,您需要等待UI调整大小并在屏幕上布局。

如果由 android:layout_width="match_parent" 设置,getWidth() 返回 0

试试这个:

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

    } 
});

您将需要使“颜色”变量finalglobal能够在listener.

于 2013-08-01T11:47:44.877 回答