Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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() {
        @Override
                public void onClick(View v) {
            ImageView p = (ImageView)findViewById(R.id.obamahere);
            p.setImageDrawable(R.drawable.brock);
        }
    });
}
like image 357
Dylan Cronkhite Avatar asked Nov 28 '22 06:11

Dylan Cronkhite


2 Answers

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:

p.setImageDrawable(myDrawable);
like image 196
Sweeper Avatar answered Nov 30 '22 19:11

Sweeper


getResources().getDrawable() deprecated API 22. You should use

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

or

ResourcesCompat.getDrawable(resources, R.drawable.name_icon, null)
like image 20
Andrey Molochko Avatar answered Nov 30 '22 20:11

Andrey Molochko