Friday, April 6, 2012

Android: Layout params programmatically.

Hi,

This is a concise tip.

To set the width, height and gravity for -say - a LinearLayout, do the following:

 LinearLayout linearLayout = (LinearLayout)findViewById(R.id.movieDetails_linearLayout);  
             
 linearLayout.setLayoutParams(new ParentView.LayoutParams(LayoutParams.WRAP_CONTENT  
                                    , LayoutParams.WRAP_CONTENT,Gravity.CENTER_HORIZONTAL));  

Note that You have to use the layout's parent when setting the parameters. ex.) if the layout's parent is a scroll view, then you'll do the following:

linearLayout.setLayoutParams(new ScrollView.LayoutParams(LayoutParams.WRAP_CONTENT  
                            , LayoutParams.WRAP_CONTENT,Gravity.CENTER_HORIZONTAL));  

That's it, don't hesitate to comment, to share your knowledge and to correct me. 

1 comment:

  1. It Helps me When My Linear Layout is inside scrollview and i need to set linear layout params programatically.

    ReplyDelete