Cómo crear Drawable from resource
Tengo una imagen res/drawable/test.png
(R.drawable.test).
Quiero pasar esta imagen a una función que acepte Drawable
.
(Por ejemplo mButton.setCompoundDrawables ())
Entonces, ¿cómo convertir un recurso de imagen en un Drawable
?
Su actividad debe tener el método getResources. Hacer:
Drawable myIcon = getResources().getDrawable( R.drawable.icon );
Este código está obsoleto.
Drawable drawable = getResources().getDrawable( R.drawable.icon );
Utilice este instad.
Drawable drawable = ContextCompat.getDrawable(getApplicationContext(),R.drawable.icon);
El getDrawable (int id)
se deprecia a partir de la API 22.
En su lugar, debe utilizar el getDrawable (int id, Resources.Theme theme)
para API 21+
El código se vería así.
Drawable myDrawable; if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP){ myDrawable = context.getResources().getDrawable(id, context.getTheme()); } else { myDrawable = context.getResources().getDrawable(id); }
Sólo me gustaría añadir que si usted está recibiendo "obsoleto" mensaje al utilizar getDrawable (…) debe utilizar el siguiente método de la biblioteca de apoyo en su lugar.
ContextCompat.getDrawable(getContext(),R.drawable.[name])
No es necesario utilizar getResources () cuando se utiliza este método.
Esto es equivalente a hacer algo como
Drawable mDrawable; if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP){ mDrawable = ContextCompat.getDrawable(getContext(),R.drawable.[name]); } else { mDrawable = getResources().getDrawable(R.id.[name]); }
Esto funciona tanto en pre y post Lollipop versiones.
Si está intentando obtener el dibujable desde la vista donde se establece la imagen como,
ivshowing.setBackgroundResource(R.drawable.one);
Entonces el drawable devolverá sólo valor nulo con el código siguiente …
Drawable drawable = (Drawable) ivshowing.getDrawable();
Por lo tanto, es mejor configurar la imagen con el código siguiente, si desea recuperar el dibujable de una vista en particular.
ivshowing.setImageResource(R.drawable.one);
Sólo entonces se convertirá el dibujable exactamente.