A Drawable
is a pluggable drawing container that is usually associated with a View. For instance, a is used to display images, a
to draw shapes and gradients, and so on. You can even combine them to create complex renderings.
As a matter of fact, they are so convenient that most of the default Android apps and widgets are built using drawables; there are about 700 drawables used in the core Android framework. Because drawables are used so extensively throughout the system, Android optimizes them when they are loaded from resources. For instance, every time you create a , a new drawable is loaded from the framework resources (
android.R.drawable.btn_default
). This means all buttons across all the apps use a different drawable instance as their background. However, all these drawables share a common state, called the "constant state." The content of this state varies according to the type of drawable you are using, but it usually contains all the properties that can be defined by a resource. In the case of a button, the constant state contains a bitmap image. This way, all buttons across all applications share the same bitmap, which saves a lot of memory.
two drawables are created but they both share the same constant state, hence the same bitmap
This state sharing feature is great to avoid wasting memory but it can cause problems when you try to modify the properties of a drawable.
使用下面代码 所有的Drawable的透明度会改变
Book book = ...;TextView listItem = ...;listItem.setText(book.getTitle());Drawable star = context.getResources().getDrawable(R.drawable.star);if (book.isFavorite()) { star.setAlpha(255); // opaque} else { star.setAlpha(70); // translucent}
android 1.5以后可使用 mutate()解决,如下代码:
Drawable star = context.getResources().getDrawable(R.drawable.star);if (book.isFavorite()) { star.mutate().setAlpha(255); // opaque} else { star. mutate().setAlpha(70); // translucent}