Search code examples
androidandroid-linearlayoutdynamic-arrays

add LinearLayout when I press "add button"


I want to add more LinearLayout in a empty one when I press "add button".

When I press the first time "it works", the empty LinearLayout show that I want but if I press the button again don't work ( LogCat show me that occurs a NullPointerException). I see that its not create a new one LinearLayout below the previous one and no idea how solve it.

Let me show you part of my code:

First, I created

static int  ID=0;
...
LinearLayout mLayout []= new LinearLayout[10];
...

OnCreate:

...
mLayout[ID] = (LinearLayout) findViewById(R.id.linearLayout_expandir);
...

Then:

private OnClickListener onClick() {
        // TODO Auto-generated method stub
         return new OnClickListener() {
                @Override
                public void onClick(View v) {

                    mLayout[ID].addView(createNewTextView("Contain: ", ID));
                    mLayout[ID].addView(createNewEditText(ID));
                    mLayout[ID].addView(createNewTextView("Nº Liter: ",ID));
                    mLayout[ID].addView(createNewEditText(ID));
                    ID++;                   
                }   
         };
    }

XML: (This LinearLayout is empty: no EditText, Buttons etc and is inside another LinearLayout)

(More code from other LinearLayouts)

 <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="0.66"
            android:orientation="horizontal" 
            android:id="@+id/linearLayout_expandir">
 </LinearLayout>

(More code from other LinearLayouts)

Thank you for your time!


Solution

  • I've created a solution for you. This activity has a button that will generate layouts for you. I use an arraylist instead of an array but the idea is the same.

    This is a picture of many nested layouts that have been created using this demo. Screenshot

    Once you get this code in your project, you will just have to add the TextView/Edit Text code that you mentioned. Let me know if you have any questions. :)

    public class LinearLayoutActivity extends Activity {
    
        /*This linear layout is the first container*/
        LinearLayout outerMostLayout;
        /*This array holds the linear layouts that you will create dynamically*/
        List<LinearLayout> subLayouts;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_linear_layout);
    
    
            // Initialize your views
            outerMostLayout = (LinearLayout) findViewById(R.id.container_layout);
            subLayouts = new ArrayList<LinearLayout>();
            Button button = (Button) findViewById(R.id.button);
    
            // Set the button onclick
            button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
    
                    // Get a reference to the container layout
                    LinearLayout container = outerMostLayout;
                    if (!subLayouts.isEmpty()) {
                        // Check to see if we have created any yet new containers yet 
                        //-- If we have, then use the newest container
                        container = subLayouts.get(subLayouts.size() - 1);
                    }
    
                    // Initialize the new layout with padding to show the change
                    LinearLayout linearLayout = new LinearLayout(LinearLayoutActivity.this);
                    linearLayout.setOrientation(LinearLayout.VERTICAL);
                    LinearLayout.LayoutParams linearLayoutParams = new LinearLayout.LayoutParams(
                            android.widget.LinearLayout.LayoutParams.MATCH_PARENT,
                            android.widget.LinearLayout.LayoutParams.MATCH_PARENT);
                    linearLayout.setLayoutParams(linearLayoutParams);
                    linearLayout.setPadding(16, 16, 16, 16);
    
                    // Add textview with linear layout name
                    TextView textView1 = new TextView(LinearLayoutActivity.this);
                    textView1.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                            ViewGroup.LayoutParams.WRAP_CONTENT));
                    textView1.setText("Linear Layout: " + (subLayouts.size() + 1));
                    textView1.setBackgroundColor(0xff66ff66); // hex color 0xAARRGGBB
                    linearLayout.addView(textView1);
    
    
                    // Add the layout to the array
                    subLayouts.add(linearLayout);
    
                    // Set the color of the new layout so that we can see the change
                    int size = subLayouts.size();
                    if (size % 2 == 0) {
                        // Every even layout will be blue
                        linearLayout.setBackgroundColor(getResources().getColor(R.color.blue));
                    } else {
                        // every odd layout will be red
                        linearLayout.setBackgroundColor(getResources().getColor(R.color.red));
                    }
    
                    // Finally, add the linear layout to the container layout
                    container.addView(linearLayout);
                }
            });
        }
    }
    

    Here is the Layout xml

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                  xmlns:tools="http://schemas.android.com/tools"
                  android:layout_width="match_parent"
                  android:layout_height="match_parent"
                  android:background="@color/red"
                  android:orientation="vertical"
                  android:paddingBottom="@dimen/activity_vertical_margin"
                  android:paddingLeft="@dimen/activity_horizontal_margin"
                  android:paddingRight="@dimen/activity_horizontal_margin"
                  android:paddingTop="@dimen/activity_vertical_margin">
    
        <Button
            android:id="@+id/button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Generate"/>
    
        <LinearLayout
            android:id="@+id/container_layout"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@color/blue"
            android:orientation="horizontal"
            android:paddingBottom="@dimen/activity_vertical_margin"
            android:paddingLeft="@dimen/activity_horizontal_margin"
            android:paddingRight="@dimen/activity_horizontal_margin"
            android:paddingTop="@dimen/activity_vertical_margin">
        </LinearLayout>
    
    </LinearLayout>