Android:背景颜色和图像同时

问题描述 投票:2回答:1

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

background:#f00 url(...);

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

谢谢

android image colors background
1个回答
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);
© www.soinside.com 2019 - 2024. All rights reserved.