VectorDrawable便利。ただ、Android4.4など古いSDKでは、注意が必要。。
基本は、Support Libraryをインポートして、AppCompatActivityとかapp:srcCompatを使うOK
ただ、Drawableを取得する際には、ContextCompatを使うだけではだめだった。。
ポイントは2つ
1. DrawableはContextCompat.getDrawable()を使って取得する
2. 取得する前にAppCompatDelegate.setCompatVectorFromResourcesEnabled(true);を実行する
2を行わないと、
Fatal Exception: android.content.res.Resources$NotFoundException If the resource you are trying to use is a vector resource, you may be referencing it in an unsupported way. See AppCompatDelegate.setCompatVectorFromResourcesEnabled() for more info.
のようなメッセージと共にandroid.content.res.Resources$NotFoundExceptionが発生する。。
build.gradle
関係あるところだけ抜粋
android {
defaultConfig {
vectorDrawables.useSupportLibrary = true // Enable Vector Drawables
}
def support_lib_ver = '27.1.+'
dependencies {
implementation "com.android.support:appcompat-v7:${support_lib_ver}"
implementation "com.android.support:support-vector-drawable:${support_lib_ver}"
implementation "com.android.support:animated-vector-drawable:${support_lib_ver}"
}
}
PicassoのプレースホルダーでVector画像を使う例
// Vector画像を利用できるように設定 AppCompatDelegate.setCompatVectorFromResourcesEnabled(true); // ContextCompatを使って読み込み Drawable drawable = ContextCompat.getDrawable(getContext(), R.drawable.ic_autorenew_48dp); // Picassoでつかう ImageView iv = new ImageView(getContext()); Picasso.get().load(url) .resizeDimen(50, 50) .centerCrop() .placeholder(drawable) .into(iv);
AppCompatDelegateについては、1度だけ実行すれば良いので、Application内とかがよいっぽい
public class AppApplication extends Application { static { AppCompatDelegate.setCompatVectorFromResourcesEnabled(true); } }