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?
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.
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));
try to set drawable like this
textview.setBackgroundDrawable( getResources().getDrawable(R.drawable.cellborder) );
visit for more help. set background drawable programmatically in Android
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.