androidandroid-layoutandroid-linearlayoutandroid-viewandroid-layoutparams

How to know which LayoutParams class to use when creating a View programmatically?


Every ViewGroup class implements a nested class that extends ViewGroup.LayoutParams. So we LinearLayout.LayoutParams, RelativeLayout.LayoutParams, FrameLayout.LayoutParams etc.

Suppose I want to create a View, e.g. TextView programmatically. I will have to give it the required properties, like layout_width and layout_height, for which I will have to use a LayoutParams class. How will I know which LayoutParams class to use?


Solution

  • It depends on what you're putting it into. If you're putting it into a linear layout, use LinearLayout.LayoutParams. For relative, use RelativeLayout.LayoutParams.

    If you don't know the type- add it first via add, then use getLayoutParams to get it. Then change the layourparams. When you use the add() that doesn't take a params, the parent will make one for you.