3

I've defined a background for my TextView:

<?xml version="1.0" encoding="utf-8"?>
<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape= "rectangle"  >
    <solid android:color="#000"/>
    <stroke android:width="1dp"  android:color="#ff9"/>
</shape>

Now I'm trying to set it to my TextView programmatically:

textview.setBackground((Drawable)findViewById(R.drawable.cellborder));

This isn't working though, it's telling me it can't cast a View as a Drawable. Is there another way to do this?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Nat
  • 53
  • 1
  • 1
  • 6

3 Answers3

5

If you want backwards compatibility then use the following:

textView.setBackground(ContextCompat.getDrawable(MainActivity.this, R.drawable.cellborder));

Replace MainActivity.this with the name of the activity from where are you calling these methods.

If you call textView.setBackground(...) from Pijamas activity then do the following:

textView.setBackground(ContextCompat.getDrawable(Pijamas.this, R.drawable.cellborder));
Gourav
  • 2,746
  • 5
  • 28
  • 45
Tudor
  • 1,510
  • 1
  • 18
  • 17
3

You have to use

getResources().getDrawable(R.drawable.cellborder);

which will return a Drawable.

If you use findViewById() it will try to find a View in the View Hierarchy and return that. A View is not a Drawable, so you can't cast it.

ci_
  • 8,594
  • 10
  • 39
  • 63
2

try to set drawable like this

textview.setBackgroundDrawable( getResources().getDrawable(R.drawable.cellborder) );

visit for more help. set background drawable programmatically in Android

Community
  • 1
  • 1
Mohammad Tauqir
  • 1,817
  • 1
  • 18
  • 53
  • 1
    This method is deprecated. use instead `tv.setBackground(ContextCompat.getDrawable(QuestionActivity.this, R.drawable.bg_shadow));` – Dharmishtha Jan 26 '21 at 12:39