新しい Android API 22getResources().getDrawable()
では非推奨になりました。最善のアプローチは、 only を使用することですgetDrawable()
。
何が変わったのですか?
新しい Android API 22getResources().getDrawable()
では非推奨になりました。最善のアプローチは、 only を使用することですgetDrawable()
。
何が変わったのですか?
ロードしているドローアブルの種類に応じて、この非推奨を適切な (および将来の保証) 方法で処理するためのいくつかのオプションがあります。
A)テーマ属性を持つドローアブル
ContextCompat.getDrawable(getActivity(), R.drawable.name);
アクティビティ テーマの指示に従って、スタイル付きの Drawable を取得します。これはおそらくあなたが必要とするものです。
B)テーマ属性のないドローアブル
ResourcesCompat.getDrawable(getResources(), R.drawable.name, null);
スタイルのないドローアブルを古い方法で取得します。注意:ResourcesCompat.getDrawable()
は非推奨ではありません!
EXTRA)別のテーマのテーマ属性を持つドローアブル
ResourcesCompat.getDrawable(getResources(), R.drawable.name, anotherTheme);
代わりに、サポート ライブラリの次のコードを使用する必要があります。
ContextCompat.getDrawable(context, R.drawable.***)
このメソッドを使用することは、次を呼び出すことと同じです。
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
return resources.getDrawable(id, context.getTheme());
} else {
return resources.getDrawable(id);
}
API 21 以降では、 のgetDrawable(int, Theme)
代わりに メソッドを使用する必要があります。このメソッドを使用getDrawable(int)
すると、特定の画面密度/テーマの特定のリソース ID に関連付けられた描画可能オブジェクトをフェッチできるからです。非推奨のgetDrawable(int)
メソッドを呼び出すことは、 を呼び出すことと同じgetDrawable(int, null)
です。
次の行を置き換えます。
getResources().getDrawable(R.drawable.your_drawable)
とResourcesCompat.getDrawable(getResources(), R.drawable.your_drawable, null)
編集
ResourcesCompat
も現在廃止されています。しかし、これを使用できます:
ContextCompat.getDrawable(this, R.drawable.your_drawable)
this
(文脈はこちら)
詳細については、このリンクに従ってください: ContextCompat
getResources().getDrawable()
は API レベル 22 で廃止されました。次に、テーマを追加する必要があります。getDrawable (int id、Resources.Theme テーマ) (API レベル 21 で追加)
これは例です:
myImgView.setImageDrawable(getResources().getDrawable(R.drawable.myimage, getApplicationContext().getTheme()));
これは、以降のバージョンを検証する方法の例です。
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { //>= API 21
myImgView.setImageDrawable(getResources().getDrawable(R.drawable.myimage, getApplicationContext().getTheme()));
} else {
myImgView.setImageDrawable(getResources().getDrawable(R.drawable.myimage));
}
使用できます
ContextCompat.getDrawable(getApplicationContext(),R.drawable.example);
それは私のための仕事です
SDK > 21 (lollipop または 5.0) をターゲットにしている場合は、
context.getDrawable(R.drawable.your_drawable_name)
en api レベル 14
marker.setIcon(ResourcesCompat.getDrawable(getResources(), R.drawable.miubicacion, null));
今、あなたはこのように実装する必要があります
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { //>= API 21
//
} else {
//
}
次の 1 行のコードで十分です。ContextCompat.getDrawable によってすべて処理されます。
ContextCompat.getDrawable(this, R.drawable.your_drawable_file)
Build.VERSION_CODES.LOLLIPOP を BuildVersionCodes.Lollipop に変更する必要があります。
if (Build.VERSION.SdkInt >= BuildVersionCodes.Lollipop) {
this.Control.Background = this.Resources.GetDrawable(Resource.Drawable.AddBorder, Context.Theme);
} else {
this.Control.Background = this.Resources.GetDrawable(Resource.Drawable.AddBorder);
}