Search code examples
androidandroid-layoutandroid-custom-view

Setting View height programmatically Android


I defined a custom view with a public method:

public void setHeight(int height) {
    //this.getLayoutParams().height = height; --- NOT WORKING
    this.setLayoutParams(new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, height)); // --- WORKING

When I use the comment out code it doesn't work (meaning that the view height is not changing when calling this method), but when I use the second phrase it's working as expected.

What can explain this behavior?


Solution

  • That's easy - just look at the code of setLayoutParams():

     public void setLayoutParams(ViewGroup.LayoutParams params) {
         if (params == null) {
             throw new NullPointerException("Layout parameters cannot be null");
         }
         mLayoutParams = params;
         if (mParent instanceof ViewGroup) {
             ((ViewGroup) mParent).onSetLayoutParams(this, params);
         }
         requestLayout();
     }
    

    See? It's calling requestLayout() after setting the layout params.

    Btw.: The Android source code can be found at www.grepcode.com and is often quite helpful.