title: Change margins inside a custom view
body: <p>In my open source library <a href="https://github.com/makovkastar/FloatingActionButton" rel="noreferrer">FloatingActioButton</a> I need to programmatically change view margins specified by a user. Margins must be reduced by a shadow size (so that margin is set to the button itself and not to the shadow).</p>
  
  <p>I override the <code>onLayout</code> of the custom view class and use the following code: </p>
  
  <pre><code>@Override
  protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
      super.onLayout(changed, left, top, right, bottom);
      if (!hasLollipopApi() &amp;&amp; !mMarginsSet) {
          if (getLayoutParams() instanceof ViewGroup.MarginLayoutParams) {
              ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) getLayoutParams();
              int leftMargin = lp.leftMargin - mShadowSize;
              int topMargin = lp.topMargin - mShadowSize;
              int rightMargin = lp.rightMargin - mShadowSize;
              int bottomMargin = lp.bottomMargin - mShadowSize;
              lp.setMargins(leftMargin, topMargin, rightMargin, bottomMargin);
  
              setLayoutParams(lp);
              mMarginsSet = true;
          }
      }
  }
  </code></pre>
  
  <p>But when I test it on the sample project I see that correct margins are applied only the first time on the first fragment (ListView). When I click on another tab, a new fragment is created (so complete layout is created) and the FAB is shifted (margins are not reduced by the shadow size):</p>
  
  <p><strong>Correct margins:</strong></p>
  
  <p><img src="https://i.stack.imgur.com/8KqeC.png" alt="Correct margins"></p>
  
  <p><strong>Wrong margins:</strong></p>
  
  <p><img src="https://i.stack.imgur.com/1AxcK.png" alt="Wrong margins"></p>
  
  <p>Even when I return to the first tab, the FAB stays with wrong margins. I tried to debug and saw that values calculated in <code>onLayout</code> are the same in all cases. Margins calculated correctly.</p>
  
  <p>Maybe <code>onLayout</code> is not correct place to change margins?</p>