Android create linearlayout programmatically

In some cases, you have to create and style a LinearLayout or RelativeLayout programmatically. Attributes that you can programmatically apply to the layout can be background color, layout width, height, margins, orientation, layout gravity, paddings, and so son.

To create a LinearLayout, you need to use LinearLayout class. You pass the current activity object to its constructor.

LinearLayout layout = new LinearLayout(MainActivity.this);

To set background color of a layout, you use setBackGroundColor(int color) method. You pass integer value that represents a color to the method. Typically I use parseColor(String color) method of Color class to convert a string hex color to its integer equivalence.


To set width and height of the layout, you have to create a LayoutParams object and set it to the layout using setLayoutParams(LayoutParam params) method. With the LayoutParams object, you also can set the left, top, right, and bottom margins of the layout.

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams
                (LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);

params.setMargins(15, 5, 5, 5);

The orientation, layout gravity, paddings of the layout can be set using the setOrientation(int orientation) and setHorizontalGravity(int horizontalGravity) or setVerticalGravity(int verticalGravity), and setPaddings(int left, int top, int right, int bottom) methods.

layout.setPadding(10, 10, 5, 5);

Posted by: Dara | post date: 04-18-2015 | Subject: Android Apps Development

write programming tip

This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.