您的位置:首页 > 其它

关于TextView的坑集合

2017-07-15 17:24 232 查看
1.关于默认字体颜色
项目中出现莫名其妙的字体不显示,实际是因为没有设置默认的字体颜色。对比检查代码没有发现style中有设置文字颜色的默认值。

通过查看 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>


暂时的解决方法是记住即使是黑色的也设置颜色值。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: