¿Cómo agrego elementos dinámicamente a una vista creada con XML?

Estoy tratando de agregar contenido dinámico a una vista que se ha creado con XML.

Tengo una vista "profile_list" que tiene un ScrollView que me gusta para agregar algunos elementos.

Aquí hay un código de lo que estoy tratando de hacer.

// Find the ScrollView 
ScrollView sv = (ScrollView) this.findViewById(R.id.scrollView1);

// Create a LinearLayout element
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);

// Add text
tv = new TextView(this);
tv.setText("my text");
ll.addView(tv);

// Add the LinearLayout element to the ScrollView
sv.addView(ll);

// Display the view
setContentView(R.layout.profile_list);

El plan es agregar un TableLayout y completarlo dinámicamente y no solo un texto ficticio, pero primero debo hacer que esto funcione .

Cualquier ayuda es bienvenida.

Saludos cordiales Olle

¡Encontré la solución!

Estúpido de mí. ¡Había dejado un elemento en mi ScrollView en mi archivo XML!

De todos modos, ella es un ejemplo de trabajo:

LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View v = inflater.inflate(R.layout.profile_list, null);

    // Find the ScrollView 
    ScrollView sv = (ScrollView) v.findViewById(R.id.scrollView1);

    // Create a LinearLayout element
    LinearLayout ll = new LinearLayout(this);
    ll.setOrientation(LinearLayout.VERTICAL);

    // Add text
    TextView tv = new TextView(this);
    tv.setText("my text");
    ll.addView(tv);

    // Add the LinearLayout element to the ScrollView
    sv.addView(ll);

    // Display the view
    setContentView(v);

Y el archivo XML para que coincida

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

    <ScrollView 
        android:id="@+id/scrollView1" 
        android:clickable="true" 
        android:layout_weight="1" 
        android:layout_width="fill_parent" 
        android:layout_marginBottom="50px" 
        android:layout_height="fill_parent">
    </ScrollView>

</LinearLayout>

Espero que esto ayude a alguien. ¡Gracias por toda la ayuda!

20
задан Marek Sebera 17 January 2013 в 15:52
поделиться