Detailed Explanation of Android LayoutParams Use Case

  • 2021-12-13 17:00:19
  • OfStack

What is LayoutParams?

LayoutParams mainly saves the layout parameters of View, so LayoutParams can be used to change the layout parameters to achieve the effect of View position, which is generally used when customizing View.

How to use LayoutParams?

If the parent control is LinearLayout, you need to use LinearLayout. LayoutParams
The code is as follows:

LinearLayout.LayoutParams layoutParams=(LinearLayout.LayoutParams)getLayoutParams();
layoutParams.leftMargin=getLeft()+offsetX;
layoutParams.topMargin=getTop()+offsetY;
setLayoutParams(layoutParams)
If the parent control is RelativeLayout, you need to use RelativeLayout. LayoutParams.

RelativeLayout.LayoutParams layoutParams=(RelativeLayout.LayoutParams)getLayoutParams();
layoutParams.leftMargin=getLeft()+offsetX;
layoutParams.topMargin=getTop()+offsetY;
setLayoutParams(layoutParams)
In addition to using the layout of LayoutParams, we can also implement it with ViewGroup. MarginLayoutParams:

ViewGroup.MarginLayoutParams layoutParams=(ViewGroup.MarginLayoutParams)getLayoutParams();
layoutParams.leftMargin=getLeft()+offsetX;
layoutParams.topMargin=getTop()+offsetY;
setLayoutParams(layoutParams);
For 1, you don't need to find the parent View, and your own new gives a custom View.

View line = null;
LayoutParams layoutParams = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 1);
layoutParams.leftMargin = 10;
line = new View(mContext);
line.setBackgroundResource(R.color.color_tie_bg);
addView(line, layoutParams);
It is realized by WindowManager. LayoutParams. The following is a code to get the size of Window. For example, when customizing Dialog, this code is written in onCreate method, so as to set dialog and finally display the size of Window.

Window win = getWindow();
WindowManager.LayoutParams lp = win.getAttributes();
lp.height = DensityUtil.dip2px(mContext, 185);
lp.width = DensityUtil.dip2px(mContext, 280);
win.setAttributes(lp);

Summarize

The above is used in the development process of some LayoutParams-related content, later will continue to supplement.


Related articles: