GetSize () no es compatible con versiones anteriores de Android OS, getWidth () / getHeight () obsoleto
Entonces, ¿cómo puedo escribir código para acomodar esto? No quiero dejar llamadas de API obsoletas en mi código, pero tampoco quiero perder a los usuarios con (un poco) dispositivos antiguos. ¿Hay algún tipo de configuración de compatibilidad que puedo implementar?
Rel. código
- Cómo tratar las clases obsoletas en Android para mantener la compatibilidad
- ¿Cómo puedo usar el mismo conjunto de pantallas de preferencias para todas las versiones de Android de 2.X a 4.X?
- ¿Por qué el teclado no se mostrará en Fragmento con WebView?
- Android: Solución para support.v4.app.Fragment -> Fragment classcastexception?
- Sustitución de fragmentos y cambio de orientación
Display display = getWindowManager().getDefaultDisplay(); Point size = new Point(); display.getSize(size); int screen_width = size.x; int screen_height = size.y;
Vs el método más antiguo:
int screen_width = getWindowManager().getDefaultDisplay().getWidth(); int screen_height = getWindowManager().getDefaultDisplay().getHeight();
- ¿Honeycomb SDK rompió la compatibilidad con versiones anteriores de GridView?
- SDK 19 y siguientes no reconoce android.support.v7.widget.CardView, Error al inflar la clase <unknown>
- ¿Cómo hacer que la función de notificación de respuesta directa de Android funcione en dispositivos pre-Android N?
- Android Lollipop - comportamiento cambiado de SQLite
- Método alternativo a TextView.getMaxLines () para Android 4.0.3 (API 15) y inferior
- Inflar ActionBarSherlock Menú definido en XML
- Inflar fragmentos con el paquete de compatibilidad android
- Android: menuItem.expandActionView () en el nivel API <14
El mejor (y por mejor, me refiero a la opción que funcionaría prácticamente cada vez) opción sería utilizar la reflexión. Echa un vistazo a las pautas de Compatibilidad con versiones anteriores de Android Backwards (actualizadas con la nueva ubicación del artículo en reflexión).
Mientras que la respuesta de tyczj funcionará perfectamente mientras las funciones obsoletas estén todavía en el SDK, tan pronto como se eliminen, no tendrás forma de usarlas o de ejecutar tu aplicación en un dispositivo antiguo si todavía quieres crear contra el SDK más reciente. .
Reflection resuelve este problema detectando dinámicamente la función en tiempo de ejecución, lo que significa que incluso si construye contra ICS, siempre y cuando la minSdkVersion sea correcta, puede hacer que su aplicación se ejecute en un dispositivo con Gingerbread o Froyo por ejemplo.
Tengo dos funciones, enviando el contexto y gettin altura y ancho en píxeles.
public static int getWidth(Context mContext){ int width=0; WindowManager wm = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE); Display display = wm.getDefaultDisplay(); if(Build.VERSION.SDK_INT>Build.VERSION_CODES.HONEYCOMB){ Point size = new Point(); display.getSize(size); width = size.x; } else{ width = display.getWidth(); // deprecated } return width; }
y
public static int getHeight(Context mContext){ int height=0; WindowManager wm = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE); Display display = wm.getDefaultDisplay(); if(Build.VERSION.SDK_INT>Build.VERSION_CODES.HONEYCOMB){ Point size = new Point(); display.getSize(size); height = size.y; }else{ height = display.getHeight(); // deprecated } return height; }
Puedes hacer algo como esto
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH){ //do stuff pertaining to this version here }else{ //other versions }
Creo que algo de lo que RivieraKid sugiere, sería algo como esto:
static Point getDisplaySize(Display d) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { return getDisplaySizeGE11(d); } return getDisplaySizeLT11(d); } @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2) static Point getDisplaySizeGE11(Display d) { Point p = new Point(0, 0); d.getSize(p); return p; } static Point getDisplaySizeLT11(Display d) { try { Method getWidth = Display.class.getMethod("getWidth", new Class[] {}); Method getHeight = Display.class.getMethod("getHeight", new Class[] {}); return new Point(((Integer) getWidth.invoke(d, (Object[]) null)).intValue(), ((Integer) getHeight.invoke(d, (Object[]) null)).intValue()); } catch (NoSuchMethodException e2) // None of these exceptions should ever occur. { return new Point(-1, -1); } catch (IllegalArgumentException e2) { return new Point(-2, -2); } catch (IllegalAccessException e2) { return new Point(-3, -3); } catch (InvocationTargetException e2) { return new Point(-4, -4); } }
Normalmente tengo una super clase es decir. BaseActivity con un método genérico para obtener un punto con el tamaño de pantalla actual. Mantiene todo agradable y limpio en la actividad real.
/** * Return screen size as a point. * @return */ @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2) @SuppressWarnings("deprecation") protected Point getSize() { final Point point = new Point(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) { getWindowManager().getDefaultDisplay().getSize(point); } else { final Display display = getWindowManager().getDefaultDisplay(); point.x = display.getWidth(); point.y = display.getHeight(); } return point; }
- Android: Cambiar la visibilidad de los elementos del menú con un fragmento cambiante
- Android 3.0, Vista previa de widgets