我正在尝试创建TextView
的自定义实现,可用于封装要显示的文本的所有所需属性。
我到目前为止所做的是:
TextAppearance
,其中包含letterSpacing
和textColor
等内容。这符合预期但当我尝试更改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" />