Android Add Views into a ViewGroup Dynamically

As Android developer you will surely  need someday to add views dynamically, instead of creating a ListView. I will show you in this tutorial how to do this 🙂

1. Create a new project and call your activity “MyActivity”
2. Go to res – layout – main.xml and put the following code:

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:id="@+id/scroll">
 
    <LinearLayout android:layout_width="fill_parent"
                  android:layout_height="wrap_content"
                  android:id="@+id/layout"
                  android:orientation="vertical"/>
</ScrollView>

3. Go to res – layout and create a new xml called text_layout.xml and put the following code:

<?xml version="1.0" encoding="utf-8"?>
 
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
          android:layout_width="fill_parent"
          android:layout_height="wrap_content"
          android:id="@+id/text"/>

4. Now go to MyActivity class and put the following code:

package com.example;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

public class MyActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

        // Parent layout
        LinearLayout parentLayout = (LinearLayout)findViewById(R.id.layout);

        // Layout inflater
        LayoutInflater layoutInflater = getLayoutInflater();
        View view;

        for (int i = 1; i < 101; i++){
            // Add the text layout to the parent layout
            view = layoutInflater.inflate(R.layout.text_layout, parentLayout, false);

            // In order to get the view we have to use the new view with text_layout in it
            TextView textView = (TextView)view.findViewById(R.id.text);
            textView.setText("Row " + i);

            // Add the text view to the parent layout
            parentLayout.addView(textView);
        }      
    }
}

And now you should have a list with 100 rows that can be scrolled.

keyboard_arrow_up
sponsored
Exit mobile version