Pregunta

Me gustaría agregar programáticamente a LinearLayout alguno TextViews.Y quiero usar LayoutInflater.Tengo en mi archivo xml de diseño de actividad:

<LinearLayout
     android:id="@+id/linear_layout"
     android:layout_width="wrap_content"
     android:layout_height="fill_parent"
     android:orientation="vertical"
     />

He escrito un código de actividad como este a continuación.

LinearLayout linearLayout = (LinearLayout) findViewById(R.id.linear_layout);
LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
TextView textView = (TextView) inflater.inflate(R.layout.scale, linearLayout, true);
textView.setText("Some text");
linearLayout.addView(textView);

Mi scale.xml el archivo se ve así:

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_weight="1"
     android:layout_marginLeft="50dp"
     android:layout_marginRight="50dp"  
     android:drawableTop="@drawable/unit"
     />

en la linea TextView textView = (TextView) inflater.inflate(R.layout.scale, linearLayout, true); Tengo una excepción fatal como esta a continuación.

 java.lang.RuntimeException: Unable to start activity ComponentInfo{my.package/my.package.MyActivity}: 
 java.lang.ClassCastException: android.widget.LinearLayout
 Caused by: java.lang.ClassCastException: android.widget.LinearLayout

Cuando reemplazo en una línea problemática linearLayout con null no tengo ninguna excepción, pero el android:layout_marginLeft y android:layout_marginRight de mi scale.xml se ignoran y no puedo ver ningún margen alrededor del TextView agregado.

he encontrado una pregunta Androide:ClassCastException al agregar una vista de encabezado a ExpandableListView pero en mi caso tengo una excepción en la primera línea en la que uso el inflador.

¿Fue útil?

Solución

Cuando especifica la vista raíz (linearLayout) en la convocatoria a inflater.inflate(), la vista ampliada se agrega automáticamente a la jerarquía de vistas.En consecuencia, no es necesario llamar addView.Además, como habrás notado, la vista devuelta es la vista raíz de la jerarquía (una LinearLayout).Para obtener una referencia a la TextView mismo, luego puedes recuperarlo con:

LinearLayout linearLayout = (LinearLayout) findViewById(R.id.linear_layout);
LayoutInflater inflater = (LayoutInflater) getApplicationContext().
    getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
inflater.inflate(R.layout.scale, linearLayout, true);
TextView textView = (TextView) linearLayout.getChildAt(
    linearLayout.getChildCount()-1);
textView.setText("Some text");

Si le dieras a la vista una android:id atributo en scale.xml, puede recuperarlo con

TextView textView = (TextView) linearLayout.findViewById(R.id.text_id);
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top