首页 > 解决方案 > 文本大纲不适用于 android X 设备

问题描述

我正在使用下面的自定义类在我的报价应用程序中制作文本大纲。它在使用 android 9 的设备之前工作正常。在 android 10 设备中,它没有给我任何错误,也没有工作。我的绘制轮廓自定义类如下所示

public class OutlineTextView extends androidx.appcompat.widget.AppCompatTextView {
    private Field colorField;
    private int textColor;
    private int outlineColor;

    public OutlineTextView(Context context) {
        this(context, null);
    }

    public OutlineTextView(Context context, AttributeSet attrs) {
        this(context, attrs, android.R.attr.textViewStyle);
    }

    public OutlineTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        try {
            colorField = TextView.class.getDeclaredField("mCurTextColor");
            colorField.setAccessible(true);


            textColor = getTextColors().getDefaultColor();
            TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.OutlineTextView);
            outlineColor = a.getColor(R.styleable.OutlineTextView_outlineColor, Color.TRANSPARENT);
            setOutlineStrokeWidth(a.getDimensionPixelSize(R.styleable.OutlineTextView_outlineWidth, 0));
            a.recycle();
        }
        catch (NoSuchFieldException e) {
            e.printStackTrace();
            colorField = null;
        }
    }

    @Override
    public void setTextColor(int color) {
        textColor = color;
        super.setTextColor(color);
    }

    public void setOutlineColor(int color) {
        invalidate();
        outlineColor = color;

    }

    public void setOutlineWidth(float width) {
        invalidate();
        setOutlineStrokeWidth(width);

    }

    private void setOutlineStrokeWidth(float width) {
        invalidate();
        getPaint().setStrokeWidth(2 * width + 1);
    }

    @Override
    protected void onDraw(Canvas canvas) {

        if (colorField != null) {
            // Outline
            setColorField(outlineColor);
            getPaint().setStyle(Paint.Style.STROKE);
            super.onDraw(canvas);

            // Reset for text
            setColorField(textColor);
            getPaint().setStyle(Paint.Style.FILL);
        }

        super.onDraw(canvas);
    }

    private void setColorField(int color) {
        // We did the null check in onDraw()
        try {
            colorField.setInt(this, color);
        }
        catch (IllegalAccessException | IllegalArgumentException e) {
            // Optionally catch Exception and remove print after testing
            e.printStackTrace();
        }
    }

}

我像这样从我的 RecyclerView 调用它

CardMainActivity.text_quotes.setOutlineColor(Color.parseColor(CardConstant.getcolorcodearray().get(getAdapterPosition())));

我的 gradle 构建信息如下

compileSdkVersion 29
buildToolsVersion "29.0.2"

让我知道是否有人可以帮助我。谢谢!

标签: javaandroid

解决方案


推荐阅读