Android:背景颜色和图像同时

时间:2014-06-17 13:51:37

标签: android image colors background

我需要同时拥有textview背景的颜色和图像,通过java而不是xml。 换句话说,我需要像这个css规则这样的东西:

background:#f00 url(...);

如何在不使用xml的情况下实现这一目标?

感谢

1 个答案:

答案 0 :(得分:9)

你不能没有xml。

第1步

创建新的Drawable资源文件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>

第2步

布局xml文件中的

<TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@drawable/textview_background" />

第3步

如果要以编程方式自定义背景:

// 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);
相关问题