Jak uzyskać obiekt Drawable z identyfikatora zasobów w pakiecie android?

Potrzebuję narysowanego obiektu do wyświetlenia na przycisku obrazu. Czy istnieje sposób na użycie poniższego kodu (lub czegoś podobnego), aby uzyskać obiekt z Androida.R. drawable.* pakiet?

Na przykład, jeśli drawableId był Androidem.R. drawable.ic_delete

mContext.getResources().getDrawable(drawableId)
Author: Brian Tompsett - 汤莱恩, 2011-10-19

4 answers

Drawable d = getResources().getDrawable(android.R.drawable.ic_dialog_email);
ImageView image = (ImageView)findViewById(R.id.image);
image.setImageDrawable(d);
 191
Author: Pete Houston,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-09-07 20:36:16

Począwszy od API 21, powinieneś używać metody getDrawable(int, Theme) zamiast getDrawable(int), ponieważ pozwala ona pobrać drawable obiekt powiązany z konkretnym resource ID dla podanego screen density/theme. Calling the deprecated getDrawable(int) metoda jest równoznaczna z wywołaniem getDrawable(int, null).

Powinieneś użyć następującego kodu z biblioteki wsparcia:

ContextCompat.getDrawable(context, android.R.drawable.ic_dialog_email)

Użycie tej metody jest równoważne wywołaniu:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    return resources.getDrawable(id, context.getTheme());
} else {
    return resources.getDrawable(id);
}
 87
Author: msoliman,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-03-29 13:03:17

Począwszy od API 21, możesz również użyć:

   ResourcesCompat.getDrawable(getResources(), R.drawable.name, null);

Zamiast ContextCompat.getDrawable(context, android.R.drawable.ic_dialog_email)

 6
Author: Zain,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-02-06 15:55:38

Najlepszy sposób to

 button.setBackgroundResource(android.R.drawable.ic_delete);

Albo to dla lewej i coś w tym stylu dla prawej itp.

int imgResource = R.drawable.left_img;
button.setCompoundDrawablesWithIntrinsicBounds(imgResource, 0, 0, 0);

I

getResources().getDrawable() is now deprecated

 2
Author: Inzimam Tariq IT,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-05-13 11:42:43