Android 修改 TextView 的全局默认颜色。
2024-08-27 18:12:27
如果你的应用中大多数TextView的颜色是红色, 或者其他颜色, 你是为每一个TextView都设置一次颜色, 还是有其他更好的办法, 这里教你怎么修改TextView的默认颜色。
当然我们TextView的远吗入手。
通过查看 TextView 源码, 发现如下代码:
public TextView(Context context, AttributeSet attrs) {
this(context, attrs, com.android.internal.R.attr.textViewStyle);
}
这段代码表示, TextView的默认样式名称是 textViewStyle。 然后在Themes.xml中的Theme下面找到 textViewStyle, 可以发现如下代码
<item name="textViewStyle">@android:style/Widget.TextView</item>
而且不同的主题TextViewStyle的值是不一样的。其中:
- Theme 下面是 @android:style/Widget.TextView;
- Theme.Height 下面没有这个值, 不知道为什么;
- Theme.Holo 下面是 :@android:style/Widget.Holo.TextView;
- Theme.Holo.Light 下面是 @android:style/Widget.Holo.Light.TextView;
接着查看源码TextView, 在509行发现如下代码:
case com.android.internal.R.styleable.TextAppearance_textColor:
textColor = appearance.getColorStateList(attr);
break;
这段代码的功能就是用于获取颜色的。 可以发现是通过com.android.internal.R.styleable.TextAppearance_textColor的值。 然后我们查看style.xml文件, 找到如下代码:
<style name="Widget.TextView">
<item name="android:textAppearance">?android:attr/textAppearanceSmall</item>
...
</style>
Widget.TextView 就是上文找的 Theme下面的TextViewStyle的值。 然后我们看到 android:textAppearance 这个就是TextView源码中提到过的。 自然接下来查看:?android:attr/textAppearanceSmall 在Theme中定义的值的是什么。
<item name="textAppearanceSmall">@android:style/TextAppearance.Small</item>
我们看到textAppearanceSmall值是 @android:style/TextAppearance.Small, 然后当然要找到@android:style/TextAppearance.Small
在style.xml中找到:
<style name="TextAppearance.Small">
<item name="android:textSize">14sp</item>
<item name="android:textColor">?textColorSecondary</item>
</style>
可以看到颜色的定义名称是 ?textColorSecondary, 到这里我们终于找到定义颜色的地方了。 这个各个主题鲜明都有定义,不止一处。
<item name="textColorSecondary">@android:color/secondary_text_dark</item>
在Theme中我们终于看到定义TextView的颜色的代码了。 比如把TextView默认颜色改为 #333333, 使用如下代码
<style name="AppTheme" parent="Theme">
<item name="android:textColorSecondary">#333333</item>
</style>
最新文章
- Nancy之基于Self Hosting的补充小Demo
- oracle查询某一个字段的数量总和
- cf#382div2
- Wix 安装部署教程(十二) -- 自动更新WXS文件
- git 简明使用手册
- [优先队列]HDOJ5360 Hiking
- 理解CRC校验
- WebKit历史项管理的实现
- [TCO 2012 Round 3A Level3] CowsMooing (数论,中国剩余定理,同余方程)
- Linux0.11小结
- restore和recover的区别
- Java学习笔记之——接口
- Codeforces Round #440 Div. 1
- 使用json web token
- iOS Xcode 10: Multiple commands produce
- java.lang.NoClassDefFoundError: org/eclipse/core/resources/IContainer
- 深入web开发之webserver/servlet容器
- 洛谷P2387 [NOI2014]魔法森林(LCT)
- codevs 1081 线段树练习 2 线段树
- java后台调用http请求