【发布时间】:2014-08-07 13:46:53
【问题描述】:
我需要通过 java 而不是 xml 同时拥有 textview 背景的颜色和图像。 换句话说,我需要这样的 CSS 规则:
background:#f00 url(...);
如何在不使用 xml 的情况下实现这一点?
谢谢
【问题讨论】:
标签: android image colors background
我需要通过 java 而不是 xml 同时拥有 textview 背景的颜色和图像。 换句话说,我需要这样的 CSS 规则:
background:#f00 url(...);
如何在不使用 xml 的情况下实现这一点?
谢谢
【问题讨论】:
标签: android image colors background
你不能没有 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);
【讨论】: