Androidでプログラム的に背景描画を設定する方法 質問する

Androidでプログラム的に背景描画を設定する方法 質問する

背景を設定するには:

RelativeLayout layout = (RelativeLayout) findViewById(R.id.background);
layout.setBackgroundResource(R.drawable.ready);

それが最善の方法でしょうか?

ベストアンサー1

layout.setBackgroundResource(R.drawable.ready);正解です。
これを実現する別の方法は、次のとおりです。

final int sdk = android.os.Build.VERSION.SDK_INT;
if(sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
    layout.setBackgroundDrawable(ContextCompat.getDrawable(context, R.drawable.ready) );
} else {
    layout.setBackground(ContextCompat.getDrawable(context, R.drawable.ready));
}

しかし、大きな画像を読み込もうとしているために問題が発生していると思います。
ここ大きなビットマップをロードする方法を説明する優れたチュートリアルです。

更新:
API レベル 22 で非推奨となった getDrawable(int ) は


getDrawable(int )、API レベル 22 で非推奨になりました。代わりに、サポート ライブラリの次のコードを使用する必要があります。

ContextCompat.getDrawable(context, R.drawable.ready)

ソースコードを参照するとコンテキストCompat.getDrawable次のような結果が表示されます。

/**
 * Return a drawable object associated with a particular resource ID.
 * <p>
 * Starting in {@link android.os.Build.VERSION_CODES#LOLLIPOP}, the returned
 * drawable will be styled for the specified Context's theme.
 *
 * @param id The desired resource identifier, as generated by the aapt tool.
 *            This integer encodes the package, type, and resource entry.
 *            The value 0 is an invalid identifier.
 * @return Drawable An object that can be used to draw this resource.
 */
public static final Drawable getDrawable(Context context, int id) {
    final int version = Build.VERSION.SDK_INT;
    if (version >= 21) {
        return ContextCompatApi21.getDrawable(context, id);
    } else {
        return context.getResources().getDrawable(id);
    }
}

詳細はコンテキスト互換性

API 22 以降では、getDrawable(int, Theme)getDrawable(int) の代わりに メソッドを使用する必要があります。

更新:
サポート v4 ライブラリを使用している場合は、以下ですべてのバージョンに十分です。

ContextCompat.getDrawable(context, R.drawable.ready)

アプリのbuild.gradleに以下を追加する必要があります。

compile 'com.android.support:support-v4:23.0.0' # or any version above

または、以下のように任意の API で ResourceCompat を使用します。

import android.support.v4.content.res.ResourcesCompat;
ResourcesCompat.getDrawable(getResources(), R.drawable.name_of_drawable, null);

おすすめ記事