Dylan Cronkhite Dylan Cronkhite - 14 days ago 4
Android Question

Android Studio - how does setImageDrawable work?

I've been trying to teach myself how to use android studio but I've hit a road block, whats wrong with this code? It wont let me use a draw-able to be set as the image?

public void obama(){
Switch s = (Switch)findViewById(R.id.obamaswitch);
s.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
ImageView p = (ImageView)findViewById(R.id.obamahere);


You need to know what is a parameter and the difference between setImageDrawable and setImageResource.

Different methods requires different parameters. And by that I mean different types of parameters. In this case, setImageDrawable requires a parameter of type Drawable but you gave it a parameter of type int. So that's why it doesn't work.

I don't know if you know this. All the resource ids (i.e. the R.xxx.xxx thingy) in Android are integers! So when you try to pass an integer when it actually needs a Drawable, it fails to do so, of course.

What you need is to either

1) Find a method that accepts an integer as a parameter. or;

2) Use the resource id to get a Drawable object.

For 1), you can use the setImageResource method. Just replace the word Drawable with Resource and change nothing else!

If you prefer 2), you can use this method to get the drawable using a resource id.

Drawable myDrawable = getResources().getDrawable(<insert your id here>);

And then you can pass myDrawable as the parameter: