Why My programatically created LinearLayouts not shown

Viewed 28

I'm trying to create a LinearLayout programmatically but for some reason it is not shown and I have no errors in Logcat or Run terminals.

Here is my Java code:

public class MainActivity extends AppCompatActivity {
    String [] arr = {"1","2","3"};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final LinearLayout parent = findViewById(R.id.rootLayout);
        LinearLayout child;

        for(int i = 0; i < arr.length; i++) {
            child = new LinearLayout(this);
            child.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
            child.setOrientation(LinearLayout.VERTICAL);
            child.setBackgroundColor(Color.YELLOW);
            parent.addView(child);
        }

    }
} 

and my XML:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rootLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">
</LinearLayout>

What I'm trying to achieve is to have 3 LinearLayouts created according to the array length as I will pass some TextViews to them later

I tried to follow the answer I found Creating LinearLayout Programmatically/Dynamically with Multiple Views but still cannot see the LinearLayouts created on the simulator.

Here is how it shows: Simulator Preview

I'm unsure what am I doing wrong?

Thank you for the hints and help.

1 Answers

Used the below and this fixed the issue:

LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
lp.height = 150;
Related