Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing LayoutParams programmatically has no effect in Android. Why?

Tags:

android

layout

I have a custom view, derived from Button, which I want to position at runtime, relative to another view. Because I don't know that other view's position yet when my view is being inflated (because layouting hasn't started), I leverage the onSizeChanged handler to set my view's position relative to the other view.

In onSizeChanged:

LayoutParams lp = new LayoutParams(this.getMeasuredWidth(), this.getMeasuredHeight());
lp.leftMargin = x;
lp.topMargin = y;
this.setLayoutParams(lp);

forceLayout();

That, however, has no effect. How come?

like image 662
Matthias Avatar asked Oct 14 '22 12:10

Matthias


1 Answers

Some things to consider:

  1. Are you sure this code is being executed?
  2. Have you examined the UI in hierarchyviewer to see if the margins are being set but they are simply not having the visual effect you expect?
  3. Are you sure this isn't better handled just via a RelativeLayout?
  4. Have you tried modifying the existing LayoutParams rather than replacing it?
like image 69
CommonsWare Avatar answered Oct 19 '22 09:10

CommonsWare