CHEAP VPS - From $2.90/Month | Cheap Dedicated Servers - From $29/Month
 

Programmatically creating layouts & views in code

June 29th, 2016

How to insert android layout by using programing code only without using xml.

this is useful in order to use for loop or building image gallery for example.

 

LinearLayout layout = new LinearLayout(this);
        layout.setOrientation(LinearLayout.VERTICAL);
 
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
             LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT
        );
        layout.setLayoutParams(params);
        setContentView(layout);
 
        TextView textView = new TextView(this);
        Button btn = new Button(this);
        btn.setText("Click Me");
 
        LinearLayout.LayoutParams textViewParams = new LinearLayout.LayoutParams(
              ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT
        );
        textView.setLayoutParams(textViewParams);
        textView.setText("Hi it's me");
 
        layout.addView(textView, params);
        layout.addView(btn,params);