在styles.xml中为TextView设置背景颜色的Android方法

7
在我的应用中,我想为TextView设置一个样式,使其看起来像以下图片中的标题-

"General" is the heading in this image.

当我应用来自styles.xml的样式(如下所示)时,它会应用指定的字体和字体颜色。但是,它不会应用白色背景。我们到底能不能做到这一点呢?

定义的样式如下-

<?xml version="1.0" encoding="utf-8"?>

<style name="settings_header">
    <item name="android:layout_marginBottom"> 10dip </item>
    <item name="android:background"> @color/white </item>
    <item name="android:paddingLeft"> 10dip </item>
    <item name="android:layout_width"> match_parent </item>
    <item name="android:layout_height"> wrap_content </item>
    <item name="android:textSize"> 22sp </item>
    <item name="android:textColor"> @color/black </item>
    <item name="android:textStyle"> bold </item>
</style>

应用样式的代码如下:

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textview = (TextView) findViewById(R.id.textView);
textview.setTextAppearance(ScrSettings.this,R.style.settings_header);
}

您确定要在白色背景上使用白色文本颜色吗? :) - Jin35
颜色只是一个例子。颜色可以是任何颜色。但重点是有一个有颜色的背景和一些文字。无论如何,已经编辑了问题。谢谢。 - Rajkiran
4个回答

1

public void setTextAppearance(Context context, int resid)

设置指定的TextAppearance资源中的文本颜色大小样式提示颜色高亮颜色

这是setTextAppearance的实际输出。在没有阅读setTextAppearance方法的行为之前,为什么要考虑背景颜色呢?

如果您想要在styles.xml中设置的所有属性,请仅在XML文件中使用style="@style/settings_header"

我希望您能理解这一点。

编辑

要在运行时设置背景颜色,请使用setBackgroundColor方法。


实际上,我想在运行时决定 TextView 的样式(标题或子标题)。我甚至尝试了 style="@style/settings_header",它工作得很好。但我不希望它是静态的即在 xml 中定义,而是希望像上面的代码一样在运行时定义。有没有其他方法在运行时设置背景颜色? - Rajkiran
不幸的是,即使是 setBackgroundColor() 也无法工作。但是 setBackgroundResource(R.color.white) 是可以工作的。但是从xml设置背景资源也应该可以工作。无论如何,将此作为答案发布。谢谢。 - Rajkiran
@Rajkiran setBackgroundColor(Color.WHITE) - 它可以工作!而setBackgroundColor(R.color.something)当然不行! - Leo

0

作为一种解决方法,这个可行

textview.setTextAppearance(context, R.style.settings_header);
textview.setBackgroundResource(R.color.white);

问题仍未得到充分回答,因为将背景设置两次到TextView并不是我们想要的。我们已经在styles.xml中设置了背景。

-2
如果你在res文件夹中没有一个名为"color"的文件夹,那么你需要用#ffffff替换@color/white。

我在colors.xml中定义了一个白色,它的值相同。我甚至尝试将#ffffff放入@color/white,但是仍然看不到背景。 - Rajkiran

-3

我不知道这是否有帮助

试试这个 @color/#fff

而不是使用“白色”

祝你好运


2
"@color/#fff" 不是一个合适的值。这甚至不能编译。而即使是 @color/#ffffff 也是错误的;因为当我们说 @color/[name] 时,它意味着我们正在调用名为 [name] 的元素。所以这不是我的问题的答案。 - Rajkiran

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接