在 Android 中为视图设置全局样式

假设我希望我的应用程序中的所有 TextView实例都具有 textColor="#ffffff"。有没有办法在一个地方设置它,而不是为每个 TextView设置它?

100586 次浏览

有两种方法可以做到这一点:

1. 使用样式

您可以通过在 res/values目录上创建 XML 文件来定义自己的样式。因此,假设您希望使用红色和粗体文本,然后创建一个包含以下内容的文件:

<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="MyRedTheme" parent="android:Theme.Light">
<item name="android:textAppearance">@style/MyRedTextAppearance</item>
</style>
<style name="MyRedTextAppearance" parent="@android:style/TextAppearance">
<item name="android:textColor">#F00</item>
<item name="android:textStyle">bold</item>
</style>
</resources>

您可以根据自己的需要来命名它,例如 res/values/red.xml。然后,你唯一需要做的事情就是在你想要的小部件中使用这个视图,例如:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
style="@style/MyRedTheme"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="This is red, isn't it?"
/>
</LinearLayout>

作为进一步的参考,您可以阅读本文: 了解 Android 的主题和风格

2. 使用定制类

这是另一种可能实现这一点的方法,它将提供您自己的 TextView,设置文本颜色始终为任何您想要的; 例如:

import android.content.Context;
import android.graphics.Color;
import android.util.AttributeSet;
import android.widget.TextView;
public class RedTextView extends TextView{
public RedTextView(Context context, AttributeSet attrs) {
super(context, attrs);
setTextColor(Color.RED);
}
}

然后,您只需将其视为 XML 文件中的一个普通 TextView:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<org.example.RedTextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="This is red, isn't it?"
/>
</LinearLayout>

你是否使用一种或另一种选择取决于你的需要。如果您唯一想做的事情是修改外观,那么最好的方法是第一种。另一方面,如果您想要改变外观并向小部件添加一些新功能,那么第二种方法是可行的。

定义一个样式并在每个小部件上使用它,定义一个覆盖该小部件的 android 默认值的主题,或者定义一个字符串资源并在每个小部件中引用它

实际上,您可以为 TextView (以及大多数其他内置小部件)设置默认样式,而无需执行自定义 Java 类或单独设置样式。

如果您查看 Android 源代码中的 themes.xml,您将看到各种小部件的默认样式的一系列属性。关键是在自定义主题中覆盖的 textViewStyle(或 editTextStyle等)属性。您可以通过以下方式覆盖它们:

创建一个 styles.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="MyTheme" parent="android:Theme">
<item name="android:textViewStyle">@style/MyTextViewStyle</item>
</style>


<style name="MyTextViewStyle" parent="android:Widget.TextView">
<item name="android:textColor">#F00</item>
<item name="android:textStyle">bold</item>
</style>
</resources>

然后将这个主题应用到 AndroidManifest.xml中的应用程序中:

<application […] android:theme="@style/MyTheme">…

所有的文本视图都将默认为 MyTextViewStyle中定义的样式(在本例中,为粗体和红色) !

这是从 API 级别4开始在设备上进行的测试,看起来效果很好。

对于 TextView中的默认文本颜色,将主题中的 android:textColorTertiary设置为所需的颜色:

<item name="android:textColorTertiary">@color/your_text_color</item>

许多其他 Android 控件的颜色可以使用框架属性进行控制,如果使用支持库,也可以使用支持库属性进行控制。

对于一个属性列表,您可以设置,检查 styles.xmlthemes.xmlAndroid 源代码,或这个非常有用的 大意由丹卢,尝试改变每个值,看看他们在屏幕上的变化。