i need to have both the color and the image for a textview background, via java and not xml. in other words, i need a thing like this css rule:
background:#f00 url(...);
how can i achieve this without use the xml?
thanks
You can't without xml.
Step 1
create new Drawable resource file textview_background.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/background" >
<shape android:shape="rectangle">
<solid android:color="COLOR"/>
</shape>
</item>
<item android:id="@+id/item_img">
<bitmap android:src="IMAGE" />
</item>
</layer-list>
Step 2
in layout xml file:
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/textview_background" />
Step 3
If you want to customize the background programatically:
// change background image
LayerDrawable layer = (LayerDrawable) textView.getBackground();
BitmapDrawable bitmap = (BitmapDrawable) resources.getDrawable(R.drawable.IMAGE);
layer.setDrawableByLayerId(R.id.item_img, bitmap);
// change background color
GradientDrawable bgShape = (GradientDrawable) textView.getBackground();
bgShape.setColor(Color.YOURCOLOR);
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