¿Cómo puedo detectar qué diseño está seleccionado por Android en mi aplicación?

Supongamos que tengo una actividad con tres diseños diferentes en carpetas de recursos diferentes. Por ejemplo:

layout-land/my_act.xml
layout-xlarge/my_act.xml
layout-xlarge-land/my_act.xml

En diferentes dispositivos y diferentes posiciones uno de ellos es seleccionado por Android.
¿Cómo puedo averiguar cuál es seleccionado por programación ?

¿Tiene Android alguna API que devuelve estos diseños al programa?


Edit : La solución de Graham Borland tiene un problema en algunas situaciones que mencioné en los comentarios.

Puede crear un directorio values-<config> para cada una de las configuraciones admitidas. Dentro de cada uno de esos directorios, cree un strings.xml con una sola cadena de configuración selected_configuration que describa la configuración actual. En tiempo de ejecución, busque la cadena utilizando el método getString estándar, que hará la resolución de configuración para usted y devolverá la cadena correcta para la configuración. Esto no ha sido probado.

Puede establecer un atributo android:tag distinto en las vistas de cada archivo de recursos diferente y leer la etiqueta en runtime con View.getTag() .

Ejemplo:

Layout-xlarge-land / my_act.xml

 <View android:id="@+id/mainview" android:tag="xlarge-landscape" /> 

Layout-xlarge / my_act.xml

 <View android:id="@+id/mainview" android:tag="xlarge-portrait" /> 

MyActivity.java

 String tag = view.getTag(); if (tag.equals("xlarge-landscape") { ... } 

Puede intentar repetir este algoritmo "Cómo Android encuentra el recurso que mejor se adapte" – es bastante simple, especialmente si tiene diseños diferentes sólo para pantallas diferentes.

Mi respuesta es implementada desde @Graham Borland

  @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); DisplayMetrics metrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(metrics); switch(metrics.densityDpi){ case DisplayMetrics.DENSITY_LOW: if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) { Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show(); String tag = view.getTag(); if (tag.equals("small-landscape") { ..... } } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) { Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show(); String tag = view.getTag(); if (tag.equals("small-potrait") { ..... } } break; case DisplayMetrics.DENSITY_MEDIUM: if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) { Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show(); String tag = view.getTag(); if (tag.equals("medium-landscape") { ..... } } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) { Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show(); String tag = view.getTag(); if (tag.equals("medium-potrait") { ..... } } break; case DisplayMetrics.DENSITY_HIGH: if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) { Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show(); String tag = view.getTag(); if (tag.equals("large-landscape") { ..... } } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) { Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show(); String tag = view.getTag(); if (tag.equals("large-potrait") { ..... } } break; } 

Esto funcionará en API lavel 4 o superior.

Estoy asumiendo que está utilizando setContentView(int resID) para establecer el contenido de sus actividades.


MÉTODO 1 (Esta es mi respuesta)

Ahora, en todos los diseños, asegúrese de que la vista de la raíz siempre tenga la etiqueta correcta:

ejemplo:

layout-xlarge/main.xml :

 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:tag="xlarge-landscape" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> </LinearLayout> 

layout-small/main.xml :

 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:tag="small" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> </LinearLayout> 

Ahora deje que sus actividades amplíen esta actividad:

 package shush.android.screendetection; import android.app.Activity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; public class SkeletonActivity extends Activity { protected String resourceType; @Override public void setContentView(int layoutResID) { LayoutInflater inflater = getLayoutInflater(); View view = inflater.inflate(layoutResID, null); resourceType = (String)view.getTag(); super.setContentView(view); } } 

En este caso, puede utilizar el tipo de resourceType para saber cuál es el identificador de recurso utilizado.


MÉTODO 2 (Esta fue mi respuesta pero antes de publicar pensé en la mejor)

Ahora, en todos los diseños, asegúrese de que la vista de la raíz siempre tenga la etiqueta correcta:

ejemplo:

layout-xlarge/main.xml :

 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:tag="xlarge-landscape" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> </LinearLayout> 

layout-small/main.xml :

 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:tag="small" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> </LinearLayout> 

Ahora deje que sus actividades amplíen esta actividad:

 package shush.android.screendetection; import android.app.Activity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; public class SkeletonActivity extends Activity { @Override public void setContentView(int layoutResID) { LayoutInflater inflater = getLayoutInflater(); View view = inflater.inflate(layoutResID, null); fix(view, view.getTag()); super.setContentView(view); } private void fix(View child, Object tag) { if (child == null) return; if (child instanceof ViewGroup) { fix((ViewGroup) child, tag); } else if (child != null) { child.setTag(tag); } } private void fix(ViewGroup parent, Object tag) { for (int i = 0; i < parent.getChildCount(); i++) { View child = parent.getChildAt(i); if (child instanceof ViewGroup) { fix((ViewGroup) child, tag); } else { fix(child, tag); } } } } 

En este caso, todas las vistas de la jerarquía tendrán la misma etiqueta.

No sé la forma exacta de encontrarlo. Pero podemos encontrarlo de manera diferente.

Agregue una vista de texto en todos los diseños (visibilidad oculta). Asigne valores como xlarge, land, xlarge-land en consecuencia.

En el programa, obtenga el valor de textview. De alguna manera podemos llegar a saber de esta manera.

Puede obtener información sobre la orientación de la pantalla y el tamaño del objeto Resources . A partir de ahí se puede entender qué disposición se utiliza.

getResources().getConfiguration().orientation; – devuelve Configuration.ORIENTATION_PORTRAIT o Configuration.ORIENTATION_LANDSCAPE .

int size = getResources().getConfiguration().screenLayout; – devuelve la máscara del tamaño de la pantalla. Puede probar contra tamaños pequeños, normales, grandes, x grandes. Por ejemplo:

 if ((size & Configuration.SCREENLAYOUT_SIZE_XLARGE)==Configuration.SCREENLAYOUT_SIZE_XLARGE) 

Su pregunta es la misma que esta ¿Cómo obtener la ruta del archivo xml de diseño?
Puede agregar una vista de texto oculto con nombres de carpeta correspondientes en el xml Obtener la cadena en la vista de texto por

 TextView path = (TextView)findViewbyid(R.id.hiddentextview); String s = path.gettext().tostring(); 

Asegúrese de que todos los id's de la vista de texto son iguales.

Ejemplo

 if your xml is in `normal-mdpi` in hidden textview hard code `normal-mdpi` if your xml is in `large-mdpi` in hidden textview hard code `large-mdpi` 
  • Formato y estilo de un recurso xml + asignar a textview
  • Cómo agregar recursos de cadena en Eclipse?
  • ADT muestra error en Strings.xml
  • Cómo limpiar un proyecto de Android?
  • ¿Qué límites hay en el número de recursos de Android?
  • ¿Por qué no se actualizan mis archivos de activos?
  • Averigüe si el recurso se utiliza
  • ¿Cómo debo almacenar cadenas comunes?
  • Android OnClickListener - identificar un botón
  • Cómo excluir archivos en carpeta "/ res" de un proyecto Android Eclipse
  • Obtener android.content.res.Resources $ NotFoundException: excepción incluso cuando el recurso está presente en android
  • FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.