Setting Layout parameters in android

大兔子大兔子 提交于 2019-11-28 19:34:36

All layout classes (LinearLayout, RelativeLayout, etc.) extend ViewGroup.

The ViewGroup class has two static inner classes: LayoutParams and MarginLayoutParams. And ViewGroup.MarginLayoutParams actually extends ViewGroup.LayoutParams.


Sometimes layout classes need extra layout information to be associated with child view. For this they define their internal static LayoutParams class. For example, LinearLayout has:

public class LinearLayout extends ViewGroup {
   ...
   public static class LayoutParams extends ViewGroup.MarginLayoutParams {  
   ...
   }
}

Same thing for RelativeLayout:

public class RelativeLayout extends ViewGroup {
   ...
   public static class LayoutParams extends ViewGroup.MarginLayoutParams {  
   ...
   }
}

But LinearLayout.LayoutParams and RelativeLayout.LayoutParams are completely different independent classes. They store different additional information about child views.

For example, LinearLayout.LayoutParams can associate weight value with each view, while RelativeLayout.LayoutParams can't. Same thing with RelativeLayout.LayoutParams: it can associate values like above, below, alightWithParent with each view. And LinearLayout.LayoutParams simply don't have these capability.


So in general, you have to use LayoutParams from enclosing layout to make your view correctly positioned and rendered. But note that all LayoutParams have same parent class ViewGroup.LayoutParams. And if you only use functionality that is defined in that class (like in your case WRAP_CONTENT and FILL_PARENT) you can get working code, even though wrong LayoutParams class was used to specify layout params.

Depending on how many views you want to change the layouts on, I think it's better to create a helper method and pass whatever views you want to change to the method along with the height and width values you want them to change to:

public void setWidthHeight(View v, int width, int height){
    LayoutParams lp;
    lp = v.getLayoutParams();
    lp.width = width;
    lp.height = height;
    v.setLayoutParams(lp);
}

Remember that setting the width and height here are not going to match the same values in your xml, i.e., android:layout_width="32dp" is not the same as lp.width = 32;

Also, the LayoutParams type variable called lp should be of the type returned by your view... Check what type is returned by the view and import that type in your import statements.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!