Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: background color and image at the same time

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

like image 809
D Ferra Avatar asked Dec 03 '22 19:12

D Ferra


1 Answers

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);
like image 181
Abdulrazak Alkl Avatar answered Dec 10 '22 11:12

Abdulrazak Alkl