Create horizontal linear layout dynamically with the use of MainActivity.java file without xml file.
Horizontal linear layout supports left to right widgets approach, When app developer selects horizontal orientation in linear layout then it will automatically start adding components and widgets to left to right side after adding them. So here is the complete step by step tutorial for Creating horizontal linearlayout programmatically android.
Creating horizontal linearlayout programmatically android.
Code for MainActivity.java file.
package com.createhorizontallinearlayoutdynamically_android_examples.com; import android.app.Activity; import android.os.Bundle; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.LinearLayout.LayoutParams; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //Creating LinearLayout. LinearLayout Horizontallinearlayout = new LinearLayout(this); //Setting up LinearLayout Orientation Horizontallinearlayout.setOrientation(LinearLayout.HORIZONTAL); LayoutParams Horizontallinearlayoutlayoutparams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); setContentView(Horizontallinearlayout, Horizontallinearlayoutlayoutparams); LayoutParams LayoutParamsview = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); //Creating textview . Button button1 = new Button(this); Button button2 = new Button(this); //Adding text to TextView. button1.setText("First Button"); button2.setText("Second Button"); button1.setLayoutParams(LayoutParamsview); button2.setLayoutParams(LayoutParamsview); //Adding textview to linear layout using Add View function. Horizontallinearlayout.addView(button1); Horizontallinearlayout.addView(button2); } }
Screenshot: