简体   繁体   中英

Android Different Ways To Add LayoutParams

I noticed there are two ways to add LayoutParams programmatically to any view and am curious to ask do they have different meanings as well.

Example 1

In this example, setting LayoutParams directly to the button.

LinearLayout parent = new LinearLayout(this);
Button btnNew = new Button(this);
LayoutParams params = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
button.setLayoutParams(params);
parent.addView(btnNew);

Example 2

In this example adding layoutparams to button when it's being added to the parent view.

LinearLayout parent = new LinearLayout(this);
Button btnNew = new Button(this);
LayoutParams params = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
parent.addView(btnNew, params);

What's different in both?

There is no difference. If you check the android source code, it specifies that if no layout params are specified, the defualts params of the view group are set. When you use the method

addView(child,params);

It calls another method named addViewInner which just sets the params object to the child object.

The source code from the ViewGroup.java can be seen here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM