使用TextAppearance的自定义TextView不能在XML中覆盖textColor

时间:2017-08-21 10:14:33

标签: android textview android-resources android-styles android-color

我正在尝试创建TextView的自定义实现,可用于封装要显示的文本的所有所需属性。

我到目前为止所做的是:

  • 应用自定义字体。
  • 应用TextAppearance,其中包含letterSpacingtextColor等内容。

这符合预期当我尝试更改XML中文本的颜色时,新文本颜色被完全忽略,文本颜色仍然是我设置的默认颜色在TextAppearance。似乎TextAppearance会覆盖XML中提供的TextView的属性。

问题:

如何使用可以在XML中修改的默认属性(主要是TextView)创建自定义textColor?请考虑此自定义TextView存在于单独模块中,与其将要使用的项目相关。

代码:

CustomTextView

public class MyTextView extends AppCompatTextView {

public MyTextView(Context context) {
    super(context);
    init(context);
}

public MyTextView(Context context, AttributeSet attrs) {
    super(context, attrs);
    init(context);
}

public MyTextView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    init(context);
}

private void init(Context context) {
    setTextAppearance(context, R.style.MyText);
    setTypeface(FontCache.futuraBookReg(getContext()));
   }
}

风格

<style name="MyText" parent="TextAppearance.AppCompat">
    <item name="android:textColor">@color/default_text_colour_selector</item>
    <item name="android:textSize">28sp</item>
    <item name="android:letterSpacing">0.04</item>
    <item name="android:lineSpacingExtra">8sp</item>
</style>

FontCache (包含完整性。即使没有自定义字体,问题仍然存在)

class FontCache {

private static final String MY_FONT = "font/my_font.ttf";

private static Map<String, Typeface> fontMap = new HashMap<>();

static Typeface myFont(Context context) {
    return getFont(context, MY_FONT);
}

private static Typeface getFont(Context context, String fontName) {
    if (fontMap.containsKey(fontName)) {
        return fontMap.get(fontName);
    } else {
        Typeface tf = Typeface.createFromAsset(context.getAssets(), fontName);
        fontMap.put(fontName, tf);
        return tf;
    }
   }
}

尝试在XML中为TextView着色

<com.example.text.MyText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColor="@color/new_text_colour"
        android:text="Hello" />

0 个答案:

没有答案