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);
}
});
}
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);
getResources().getDrawable() deprecated API 22. You should use
ContextCompat.getDrawable(context, R.drawable.name_icon)
or
ResourcesCompat.getDrawable(resources, R.drawable.name_icon, null)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With