Reputation: 1486
I'm creating a ImageView programmatically :
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
also after doing some search in the docs i found requestLayout()
might solve this, but it doesnt help either
public void setMargins (int left, int top, int right, int bottom)
Sets the margins, in pixels. A call to requestLayout() needs to be done so that the new margins are taken into account. Left and right margins may be overriden by requestLayout() depending on layout direction.
UPDATE
if i call color.getX()
inside onClick listener it returns 4 as expected
Upvotes: 2
Views: 1213
Reputation: 8145
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.
getWidth() returns 0 if set by android: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
.
Upvotes: 3