Android: Change absolute position of a view programmatically Android: Change absolute position of a view programmatically android android

Android: Change absolute position of a view programmatically


Use the version of addView that takes LayoutParams:

LayoutParams params = mLayout.generateLayoutParams();params.x = remoteObject.x;params.y = remoteObject.y;mLayout.addView(button, params);


In response to your comment on Mayra's answer, I had a similar issue with RelativeLayout instead of AbsoluteLayout. The solution was to use a similar method and cast it as your layout type. Something like this:

LayoutParams params = (android.widget.RelativeLayout.LayoutParams) this.generateDefaultLayoutParams();params.height = 360;params.width = 360;params.addRule(CENTER_IN_PARENT);this.addView(board, params);

It took me forever to figure this out so I wanted to post it here for someone else if they needed it.


I had just the same problem but found a somewhat different solution.

int width = 100, height = 50, x = 10, y = 20;Button button = new Button(this);AbsoluteLayout myLayout = (AbsoluteLayout)findViewById(R.id.myLayout);myLayout.add(button, new AbsoluteLayout.LayoutParams(width, height, x, y));

And if you find out what to use for "fill_parent" (hint try -1) then you may use those constants for width and height.