2017-01-16 8 views
0

私は背景の描画可能なイメージを私が持っているrelativelayoutに設定しようとしています。私はsetBackgroundを使用していて、intではなくdrawableを要求します。私はそれにdrawableを与えることができ、それはまだ私にエラーを与える。ここで私のコードのセクション。relativelayoutの背景画像を設定しようとしています

rl.setBackground(R.drawable.loginbackground3); 

これはエラーです。

setBackground (android.graphics.drawable.Drawable) in View cannot be applied to (int). 

非常に混乱して助けてください?

答えて

1

これを試してください:あなたはサポートライブラリを使用している場合は、そのようなgetDrawableの廃止を解決できることを

Drawable background = rl.getContext().getResources().getDrawable(R.drawable.loginbackground3); 
rl.setBackground(background); 

注意そのような場合は、ビルドバージョンを確認する必要があります(下位バージョン用にビルドしている場合)。

あなたのレイアウトがrelativelayout1命名されたと仮定し
final int sdk = android.os.Build.VERSION.SDK_INT; 
if(sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) { 
    rl.setBackgroundDrawable(getResources().getDrawable(R.drawable.loginbackground3)); 
} else { 
    rl.setBackground(getResources().getDrawable(R.drawable.loginbackground3)); 
} 
+0

私はrl.setBackgroundResource(R.drawable.loginbackground3)を使ってみました。そして、私はエラーは表示されませんが、動作しません。何も起こりません。背景は変わらない –

1

ドロアブルの参照を使用してドロワブルをロードする必要があります。あなたがしたい場合は

rl.setBackgroundResource(R.drawable.loginbackground3); 

のか:

Drawable background = ContextCompat.getDrawable(rl.getContext(), R.drawable.loginbackground3); 
rl.setBackground(background); 
+0

ライン上のエラーを取得してイム:Drawableの背景= rl.getContext()getResources()getDrawable(R.drawable.loginbackground3);。。 エラー:android.content.Context android.widget.RelativeLayout.getContext() 'ヌルオブジェクトリファレンス –

0

//: はまず、そのためのAndroid自体からのライブラリの矛盾の

RelativeLayout r1 = (RelativeLayout) findViewById(R.id.relativelayout1); 
r1.setBackgroundResource(R.drawable.sample); 
0

、あなたが方法getDrawableを作成する必要があります。

private Drawable getDrawable(int id) { 
    final int sdk = android.os.Build.VERSION.SDK_INT; 
    if (sdk >= android.os.Build.VERSION_CODES.LOLLIPOP) { 
    return ContextCompat.getDrawable(getContext(), id); 
    } else { 
    return getContext().getResources().getDrawable(id); 
    } 
} 

その後、メソッドを作成するsetBackgroundView:

private void setBackgroundView(View v, int drawable_Rid) { 
    Drawable background = getDrawable(drawable_Rid); 
    final int sdk = android.os.Build.VERSION.SDK_INT; 
    if (sdk >= android.os.Build.VERSION_CODES.JELLY_BEAN) { 
    v.setBackground(background); 
    } else { 
    v.setBackgroundDrawable(background); 
    } 
} 

そして最後に、このように描画可能な名前でsetBackgroundViewを呼び出します。

setBackgroundView(rl, R.drawable.loginbackground3); 
関連する問題