0

I am trying to cast a drawable in my code but I get this error

An instance of type android.view.View' can not be of type android.graphics.drawable.Drawable

Here is my code:

mydrawable = (Drawable) findViewById(R.drawable.mydrawable); 
3
  • findViewById it means this is a View. It can't be casted as Drawable. Commented May 3, 2018 at 13:13
  • Because this not the way to get a drawable, check this Commented May 3, 2018 at 13:13
  • Refer this :- stackoverflow.com/a/29146895/3974530 Commented May 3, 2018 at 13:34

2 Answers 2

0

Return type of findViewById() is a View which cannot be casted to Drawable.

Replace

(Drawable) findViewById(R.drawable.mydrawable); 

with

ContextCompat.getDrawable(getActivity(), R.drawable.mydrawable); 
Sign up to request clarification or add additional context in comments.

Comments

0

You can't cast this View as Drawable. You can cast this as EditText, TextView because those finally extend the class View. But Drawable doesn't extend View.

Try this

mydrawable = ResourcesCompat.getDrawable(getResources(), R.drawable.mydrawable, null); 

This will be type of android.graphics.drawable.Drawable and your problem may be solved.

3 Comments

@cricket_007 did you mean getBaseContext() ?
Actually, nevermind, getting resources was right developer.android.com/reference/android/support/v4/content/res/…
@cricket_007 Okay than 😐.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.