Search code examples
javaandroidandroid-drawable

Programmatically setting TextView background


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?


Solution

  • 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.