我有一个LinearLayout,其中有多个TextView,并希望仅为该布局设置默认全局颜色,而无需在每个TextView中添加textColor
字段。此外,如果可能的话,是否也可以通过在TextView中添加它来覆盖颜色值?例如,如果我将蓝色设置为默认颜色,并将黑色设置为单个TextView的颜色,那么蓝色会变成黑色吗?
我有一个LinearLayout,其中有多个TextView,并希望仅为该布局设置默认全局颜色,而无需在每个TextView中添加textColor
字段。此外,如果可能的话,是否也可以通过在TextView中添加它来覆盖颜色值?例如,如果我将蓝色设置为默认颜色,并将黑色设置为单个TextView的颜色,那么蓝色会变成黑色吗?
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
<item name="textColorPrimary">@color/black</item>
<item name="textColorSecondary">@color/grey</item>
</style>
为了设置默认的全局TextView颜色,您首先可以在AndroidManifest.xml
文件中为以下项目创建自己的主题:
textColorPrimary
- 用于大文本textColorSecondary
- 用于中等文本textColorTertiary
- 用于小型文本textColorHint
- 用于提示文本例如,在AndroidManifest.xml
中:
<style name="TextViewTheme" parent="android:Widget.TextView">
<!-- Set the default global color for TextViews to Holo Blue Dark -->
<item name="android:textColorPrimary">@android:color/holo_blue_dark</item>
<item name="android:textColorSecondary">@android:color/holo_blue_dark</item>
<item name="android:textColorTertiary">@android:color/holo_blue_dark</item>
<item name="android:textColorHint">@android:color/holo_blue_dark</item>
</style>
接下来,在您的LinearLayout上设置主题样式。您还可以为单个TextView覆盖默认值,例如在activity_main.xml
中将第一个TextView的Hint文本颜色设置为黑色,如下所示:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:theme="@style/TextViewTheme">
<TextView
android:id="@+id/phone_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="@string/phone_tv"
android:textColor="@android:color/black"
android:textColorHint="@android:color/black" />
<TextView
android:id="@+id/email_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="@string/email_tv" />
</LinearLayout>
即使您在布局中添加或删除TextViews,此代码也能正常工作。只需将其放入活动的onCreate()
中即可;
LinearLayout layout = (LinearLayout)findViewById(R.id.layout);
for (int i = 0; i < layout.getChildCount(); i++) {
View v = layout.getChildAt(i);
if (v instanceof TextView) {
((TextView) v).setTextColor(Color.BLACK);
}
}
将颜色更改为您喜欢的颜色。
如果您想在此代码之后更改任何特定TextView的颜色,可以这样做。
style.xml
中最近更改为 themes.xml
。<style name="ErrorStyle">
<item name="android:textColor">#FF0000</item>
</style>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:theme="@style/ErrorStyle">
.. All of your TextView
</LinearLayout>