Reputation: 23
I am trying to set a background drawable image to a relativelayout that i have. I am using setBackground and it asks for a drawable not an int. I can giving it a drawable and it stills gives me an error. Here a section of my code.
rl.setBackground(R.drawable.loginbackground3);
This is the error I'm getting.
setBackground (android.graphics.drawable.Drawable) in View cannot be applied to (int).
Very confused please help?
Upvotes: 0
Views: 1566
Reputation: 5821
Because of inconsistency of library from android itself, First, you need to create method 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);
}
}
Then, create method 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);
}
}
And finally call the setBackgroundView with drawable name like this :
setBackgroundView(rl, R.drawable.loginbackground3);
Upvotes: 0
Reputation: 2819
Try this:
rl.setBackgroundResource(R.drawable.loginbackground3);
or if you want to do like yours in that case you need to check build version(if you are building for lower version's).
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));
}
Upvotes: 2
Reputation: 984
//assuming your Layout is named relativelayout1:
RelativeLayout r1 = (RelativeLayout) findViewById(R.id.relativelayout1);
r1.setBackgroundResource(R.drawable.sample);
Upvotes: 0
Reputation: 31
You need to load the drawable using that drawable reference.
Drawable background = rl.getContext().getResources().getDrawable(R.drawable.loginbackground3);
rl.setBackground(background);
Note that if you're using the support libraries you can solve the deprecation of getDrawable like so:
Drawable background = ContextCompat.getDrawable(rl.getContext(), R.drawable.loginbackground3);
rl.setBackground(background);
Upvotes: 1