RelativeLayout layout =(RelativeLayout)findViewById(R.id.background);
layout.setBackgroundResource(R.drawable.ready);
Is the best way to do it?
This question is related to
java
android
background
drawable
if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN)
layout.setBackgroundDrawable(getResources().getDrawable(R.drawable.ready));
else if(android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP_MR1)
layout.setBackground(getResources().getDrawable(R.drawable.ready));
else
layout.setBackground(ContextCompat.getDrawable(this, R.drawable.ready));
Try this:
layout.setBackground(ContextCompat.getDrawable(context, R.drawable.ready));
and for API 16<:
layout.setBackgroundDrawable(ContextCompat.getDrawable(context, R.drawable.ready));
I'm using a minSdkVersion 16 and targetSdkVersion 23.
The following is working for me, it uses
ContextCompat.getDrawable(context, R.drawable.drawable);
Instead of using:
layout.setBackgroundResource(R.drawable.ready);
Rather use:
layout.setBackground(ContextCompat.getDrawable(this, R.drawable.ready));
getActivity()
is used in a fragment, if calling from a activity use this
.
setBackground(getContext().getResources().getDrawable(R.drawable.green_rounded_frame));
Use butterknife to bind the drawable resource to a variable by adding this to the top of your class (before any methods).
@Bind(R.id.some_layout)
RelativeLayout layout;
@BindDrawable(R.drawable.some_drawable)
Drawable background;
then inside one of your methods add
layout.setBackground(background);
That's all you need
RelativeLayout relativeLayout; //declare this globally
now, inside any function like onCreate, onResume
relativeLayout = new RelativeLayout(this);
relativeLayout.setBackgroundResource(R.drawable.view); //or whatever your image is
setContentView(relativeLayout); //you might be forgetting this
If your backgrounds are in the drawable folder right now try moving the images from drawable to drawable-nodpi folder in your project. This worked for me, seems that else the images are rescaled by them self..
Try this code:
Drawable thumb = ContextCompat.getDrawable(getActivity(), R.mipmap.cir_32);
mSeekBar.setThumb(thumb);
try this.
int res = getResources().getIdentifier("you_image", "drawable", "com.my.package");
preview = (ImageView) findViewById(R.id.preview);
preview.setBackgroundResource(res);
Inside the app/res/your_xml_layout_file.xml
You can also set the background of any Image:
View v;
Drawable image=(Drawable)getResources().getDrawable(R.drawable.img);
(ImageView)v.setBackground(image);
Give a try to ViewCompat.setBackground(yourView, drawableBackground)
Source: Stackoverflow.com