0

How would I go about adding layouts that contain different objects dynamically with code.

For example I've made a perfect "Prefab" layout which has everything I need in it (other layouts, text views, buttons etc).

I would like to be able to recreate this exact same layout in code, so when I run the app it will create a multitude of these.

Any ideas?

Al Lelopath
  • 6,448
  • 13
  • 82
  • 139

1 Answers1

0

For static layouts XML is the preferred choice. However, you can create any layout in code dynamically inside your Java (or Kotlin) code. Since you haven't asked for a specific layout creation I'm providing you with a sample code in which you can see how layouts are created in Java without inflating XML files:

STEP 1 - Create Java objects for all Views and ViewGroups

LinearLayout ll = new LinearLayout(Context object);

// Context object is nothing but a way to access system resources and services in Android OS (we will use 'this') Also Context is the super class of Activity

TextView tv = new TextView(Context object);
Button b = new Button(Context object);

STEP 2 - Define dimensions for all Views and ViewsGroups. Specify layout information for each child using LinearLayout.LayoutParams object

LinearLayout.LayoutParams dimensions = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
ll.setLayoutParams(dimensions);
LinearLayout.LayoutParams dimensions2 = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(dimensions2);
b.setLayoutParams(dimensions2);

STEP 3 - Set other properties of our Views and ViewGroups like color, size, gravity etc.

ll.setOrientation(LinearLayout.VERTICAL);
tv.setText("some text");
b.setText("Button");

STEP 4 - Add all the Views to the root ViewGroup in the respective order

ll.addView(tv);
ll.addView(b);

STEP 5 - Set the content view to the root layout. (by calling the setContentView() method inside onCreate() method of the activity)

setContentView(ll);
Sergey Emeliyanov
  • 5,158
  • 6
  • 29
  • 52