我的应用程序中有一个日历。日历是一个带有每个日期按钮的 GridView。我尝试用下面的课程给它们上色
public class CircleSpan extends ReplacementSpan {
private final float mPadding;
private final int mCircleColor;
private final int mTextColor;
public CircleSpan(Context context) {
super();
TypedArray ta = context.getTheme().obtainStyledAttributes(new int[]{
R.color.current_day,
android.R.attr.textColorPrimaryInverse
});
mCircleColor = ta.getColor(0, ContextCompat.getColor(context, R.color.current_day));
//noinspection ResourceType
mTextColor = ta.getColor(1, 0);
ta.recycle();
mPadding = context.getResources().getDimension(R.dimen.padding_circle);
}
@Override
public int getSize(Paint paint, CharSequence text, int start, int end, Paint.FontMetricsInt fm) {
Log.d("CircleSpan", "getSize");
return Math.round(paint.measureText(text, start, end) + mPadding * 2); // left + right
}
@Override
public void draw(Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, Paint paint) {
if (TextUtils.isEmpty(text)) {
Log.d("CircleSpan", "empty draw");
return;
}
float textSize = paint.measureText(text, start, end);
paint.setColor(mCircleColor);
canvas.drawCircle(x + textSize / 2 + mPadding,
(top + bottom) / 2, // center Y
(text.length() == 1 ? textSize : textSize / 2) + mPadding,
paint);
paint.setColor(mTextColor);
canvas.drawText(text, start, end, mPadding + x, y, paint);
Log.d("CircleSpan", "draw");
}
}
我创建了该类并使用棒棒糖测试设备对其进行了测试,一切正常。之后,我将应用程序与 Marshmallow 一起放置在我的设备上。日历内应具有颜色的条目不再可见。我发现我的 CircleSpan 类中的绘制方法甚至没有被调用。
通过一点“黑客”,我能够让它工作,但我对这个解决方案真的不满意。它由一个在屏幕末端不可见的 TextView 组成,该 TextView 也使用 CircleSpan 进行着色。区别在于文本的扩展,并且只为除扩展之外的所有内容着色:
// Absolutly hacked
SpannableString spannable1 = new SpannableString(theday + " ");
spannable1.setSpan(new CircleSpan(gridcell.getContext(), ColorType.NONE),
0, theday.length() - 1,
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
mHack.setText(spannable1, TextView.BufferType.SPANNABLE);
只要“黑客”位于应用程序内部,其他所有内容都会像我编码的那样着色。但我真的不知道为什么。我在 Android 文档中阅读了有关 ReplacementSpan 的内容:ReplacementSpan 获取大小 https://developer.android.com/reference/android/text/style/ReplacementSpan.html#getSize(android.graphics.Paint,%20java.lang.CharSequence,%20int,%20int,%20android.graphics.Paint.FontMetricsInt)
但线索
返回跨度的宽度。扩展类可以通过更新 Paint.FontMetricsInt 的属性来设置跨度的高度。如果span覆盖整个文本,并且未设置高度,则不会为span调用draw(Canvas, CharSequence, int, int, float, int, int, int, Paint)。
对我没有帮助。有谁知道如何在没有“黑客”的情况下用我的班级为我的日历条目着色?为什么问题只出现在 Marshmallow 设备上?我不确定 Nougat 以及 Lollipop 以下设备上发生的情况。
我希望每个人都能理解我蹩脚的英语。提前致谢!