Android create vertical linearlayout programmatically

Creating vertical LinearLayout dynamically using only MainActivity.java coding file without xml file.

Vertical linear layout gives top to bottom approach in android application means widgets can automatically added one by one into vertically form. So here is the complete step by step tutorial for Android create vertical linearlayout programmatically.

android-project-download-code-button

Android create vertical linearlayout programmatically.

Code for MainActivity.java file.

 package com.createlinearlayoutprogrammatically_android_examples.com;

import android.app.Activity;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;

public class MainActivity extends Activity {

 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 
 //Creating LinearLayout.
 LinearLayout linearlayout = new LinearLayout(this);
 
 //Setting up LinearLayout Orientation
 linearlayout.setOrientation(LinearLayout.VERTICAL);
 
 LayoutParams linearlayoutlayoutparams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); 
 
 setContentView(linearlayout, linearlayoutlayoutparams);
 
 LayoutParams LayoutParamsview = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
 
 //Creating textview .
 TextView SampleTextView1 = new TextView(this);
 TextView SampleTextView2 = new TextView(this);
 
 //Adding text to TextView.
 SampleTextView1.setText("First TextView Text");
 SampleTextView2.setText("Second TextView Text");
 
 //Setting TextView text Size 
 SampleTextView1.setTextSize(25);
 SampleTextView2.setTextSize(25);
 
 SampleTextView1.setLayoutParams(LayoutParamsview);
 SampleTextView2.setLayoutParams(LayoutParamsview);
 
 //Adding textview to linear layout using Add View function.
 linearlayout.addView(SampleTextView1);
 linearlayout.addView(SampleTextView2);
 
 }
}

Screenshot:

Android create vertical linearlayout programmatically

Click here to download Android create vertical linearlayout programmatically project.

Leave a Reply

Your email address will not be published. Required fields are marked *