Cómo inflar una vista con un diseño


Tengo un layout definido en XML. Contiene también:

<RelativeLayout
    android:id="@+id/item"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
/>

Me gustaría inflar este RelativeView con otro archivo de diseño XML. Puedo usar diferentes diseños dependiendo de una situación. ¿Cómo debería hacerlo? Estaba probando diferentes variaciones de

RelativeLayout item = (RelativeLayout) findViewById(R.id.item);
item.inflate(...)

Pero ninguno de ellos funcionó bien.

Author: Jeb_is_a_mess, 2010-02-25

14 answers

No estoy seguro de haber seguido su pregunta - ¿está tratando de adjuntar una vista de niño al RelativeLayout? Si es así, desea hacer algo en las líneas de:

RelativeLayout item = (RelativeLayout)findViewById(R.id.item);
View child = getLayoutInflater().inflate(R.layout.child, null);
item.addView(child);
 346
Author: Graeme Duncan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-02-03 18:47:07

Se infla un recurso XML. Véase el doc LayoutInflater .

Si su presentación es en un mipresentación.xml , usted haría algo como:

View view; 
LayoutInflater inflater = (LayoutInflater)   getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
view = inflater.inflate(R.layout.mylayout, null);

RelativeLayout item = (RelativeLayout) view.findViewById(R.id.item);
 99
Author: ccheneson,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-02-25 16:54:31

Aunque respuesta tardía, pero me gustaría añadir que una manera de obtener esto

LayoutInflater layoutInflater = (LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View view = layoutInflater.inflate(R.layout.mylayout, item );

Donde item es el diseño padre donde desea agregar un diseño hijo.

 23
Author: Shaista Naaz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-15 10:58:59

Es útil agregar a esto, a pesar de que es un post antiguo, que si la vista hija que se está inflando desde xml se va a agregar a un diseño de viewgroup, debe llamar a inflate con una pista de a qué tipo de viewgroup se va a agregar. Como:

View child = getLayoutInflater().inflate(R.layout.child, item, false);

El método inflate está bastante sobrecargado y describe esta parte del uso en los documentos. Tuve un problema en el que una sola vista inflada de xml no se alineaba correctamente en el padre hasta que hice este tipo de cambio.

 18
Author: Maximus,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-06-01 22:59:13

Una forma aún más sencilla es usar

View child = View.inflate(context, R.layout.child, null)
item.addChild(child) //attach to your item
 9
Author: Ashish Rawat,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-09-02 02:43:05

Inflación de diseño

View view = null;
LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
view = inflater.inflate(R.layout.mylayout, null);
main.addView(view);
 8
Author: Happy Singh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-30 11:26:02

Si no estás en una actividad puedes usar el método estático from() de la clase LayoutInflater para obtener un LayoutInflater, o solicitar el servicio desde el método context getSystemService() también:

LayoutInflater i;
Context x;       //Assuming here that x is a valid context, not null

i = (LayoutInflater) x.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//OR
i = LayoutInflater.from(x);

(Sé que es hace casi 4 años, pero aún vale la pena mencionarlo)

 6
Author: Juan Cortés,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-02-06 22:04:07

Compruebe este Enlace. Tiene la respuesta - > https://possiblemobile.com/2013/05/layout-inflation-as-intended /

 4
Author: Akshayraj Kore,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-10-19 19:29:33

Si desea agregar una sola vista varias veces, debe usar

   layoutInflaterForButton = getActivity().getLayoutInflater();

 for (int noOfButton = 0; noOfButton < 5; noOfButton++) {
        FrameLayout btnView = (FrameLayout) layoutInflaterForButton.inflate(R.layout.poll_button, null);
        btnContainer.addView(btnView);
    }

Si te gusta

   layoutInflaterForButton = getActivity().getLayoutInflater();
    FrameLayout btnView = (FrameLayout) layoutInflaterForButton.inflate(R.layout.poll_button, null);

Y

for (int noOfButton = 0; noOfButton < 5; noOfButton++) {
            btnContainer.addView(btnView);
        }

Entonces lanzará la excepción de la vista agregada lista.

 3
Author: John smith,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-27 11:09:47

Tuve el tiempo más difícil con este error, debido a mis circunstancias únicas, pero finalmente encontré una solución.

Mi situación: Estoy usando una vista separada (XML) que contiene un WebView, luego se abre en un AlertDialog cuando hago clic en un botón en mi vista de actividad principal. Pero de alguna manera u otra la WebView pertenecía a la vista principal de la actividad (probablemente porque saco el recurso de aquí), así que justo antes de asignarlo a mi AlertDialog (como una vista), tuve que obtener el padre de mi WebView, ponerlo en una ViewGroup, luego elimine todas las vistas en ese ViewGroup. Esto funcionó, y mi error desapareció.

// set up Alert Dialog box
AlertDialog.Builder alert = new AlertDialog.Builder(this);
// inflate other xml where WebView is
LayoutInflater layoutInflater = (LayoutInflater)this.getSystemService
                (Context.LAYOUT_INFLATER_SERVICE);
View v = layoutInflater.inflate(R.layout.your_webview_layout, null);
final WebView webView = (WebView) v.findViewById(R.id.your_webview_id);

// more code...

.... más tarde después de cargar mi WebView ....

// first, remove the parent of WebView from it's old parent so can be assigned a new one.
ViewGroup vg = (ViewGroup) webView.getParent();
vg.removeAllViews();

// put WebView in Dialog box
alert.setView(webView);
alert.show();
 2
Author: Azurespot,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-21 03:37:55

Con Kotlin, puedes usar:

val content = LayoutInflater.from(context).inflate(R.layout.[custom_layout_name], null)

[your_main_layout].apply {
    //..
    addView(content)
}
 1
Author: Hasan A Yousef,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-26 18:06:58

Si está intentando adjuntar una vista hija al RelativeLayout? puede hacerlo siguiendo

RelativeLayout item = (RelativeLayout)findViewById(R.id.item);
View child = getLayoutInflater().inflate(R.layout.child, item, true);
 1
Author: Kasim Rangwala,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-28 09:27:06

AttachToRoot Establecido en True

Solo piense que especificamos un botón en un archivo de diseño XML con su ancho de diseño y altura de diseño configurados en match_parent.

<Button xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/custom_button">
</Button>

En Este Evento de Clic de Botones Podemos Establecer El Siguiente Código para Inflar El Diseño de Esta Actividad.

LayoutInflater inflater = LayoutInflater.from(getContext());
inflater.inflate(R.layout.yourlayoutname, this);

Espero que esta solución funcione para usted.!

 1
Author: eSparkBiz Team,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-17 08:55:28

Había usado el siguiente fragmento de código para esto y funcionó para mí.

LinearLayout linearLayout = (LinearLayout)findViewById(R.id.item);
View child = getLayoutInflater().inflate(R.layout.child, null);
linearLayout.addView(child);
 -1
Author: Mahak,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-11-23 11:37:26