Diseño de Android reemplazar una vista con otra vista en tiempo de ejecución


Tengo un archivo de diseño xml principal con dos vistas de texto A / B y una vista C. Que tengo otros dos archivos de diseño xml option1 y option2. ¿Es posible cargar option1 o option2 en tiempo de ejecución a través de Java en C? Si es así, ¿qué función tengo que usar?

Author: Christian, 2010-07-26

3 answers

Puede reemplazar cualquier vista en cualquier momento.

int optionId = someExpression ? R.layout.option1 : R.layout.option2;

View C = findViewById(R.id.C);
ViewGroup parent = (ViewGroup) C.getParent();
int index = parent.indexOfChild(C);
parent.removeView(C);
C = getLayoutInflater().inflate(optionId, parent, false);
parent.addView(C, index);

Si no desea reemplazar la vista ya existente , pero elija entre option1 / option2 en el momento de la inicialización, entonces podría hacerlo más fácil: establecer android:id para el diseño padre y luego:

ViewGroup parent = (ViewGroup) findViewById(R.id.parent);
View C = getLayoutInflater().inflate(optionId, parent, false);
parent.addView(C, index);

Tendrá que establecer "index" en el valor adecuado dependiendo de la estructura de las vistas. También puede usar un ViewStub : agregue su vista C como ViewStub y luego:

ViewStub C = (ViewStub) findViewById(R.id.C);
C.setLayoutResource(optionId);
C.inflate();

De esa manera no tendrás que preocuparte por lo anterior " index" valor si desea reestructurar su diseño XML.

 339
Author: broot,
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
2017-01-04 14:16:06

Y si lo hace muy a menudo, podría usar un ViewSwitcher o un ViewFlipper para facilitar la sustitución de vistas.

 39
Author: Snicolas,
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-12-12 06:05:55

Funciona en mi caso, oldSensor y Newssor-oldView y newView:

private void replaceSensors(View oldSensor, View newSensor) {
            ViewGroup parent = (ViewGroup) oldSensor.getParent();

            if (parent == null) {
                return;
            }

            int indexOldSensor = parent.indexOfChild(oldSensor);
            int indexNewSensor = parent.indexOfChild(newSensor);
            parent.removeView(oldSensor);
            parent.addView(oldSensor, indexNewSensor);
            parent.removeView(newSensor);
            parent.addView(newSensor, indexOldSensor);
        }
 0
Author: ch13mob,
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-06 14:42:27