绘制StaticLayout无法正常工作

时间:2017-09-16 12:10:35

标签: java android staticlayout

我已经使用View实施了Text.Layout并且我正在绘制它,但我什么都没得到。这是我的代码

public class MyEfficientTextView extends View {
    Layout textLayout;
    SpannableStringBuilder spannableStringBuilder;
    int width = 0, height = 0;
    TextPaint textPaint;
    CharSequence text;

    public MyEfficientTextView(Context context) {
        this(context, null, 0);
    }

    public MyEfficientTextView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public MyEfficientTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        spannableStringBuilder = new SpannableStringBuilder();
    }

    public void setText(CharSequence charSequence) {
        text = charSequence;
        spannableStringBuilder.clear();
        spannableStringBuilder.append(text);
        textPaint = new TextPaint();
        textPaint.setAntiAlias(true);
        textPaint.setTextSize(16 * getResources().getDisplayMetrics().density);
        textPaint.setColor(getResources().getColor(R.color.textColor));
        textLayout = new StaticLayout(spannableStringBuilder, textPaint, width, Layout.Alignment.ALIGN_NORMAL, 1, 0, false);
        invalidate();
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        if (w != width) {
            width = w;
            setText(text);
        }
        height = h;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.save();
        if (textLayout != null) {
            canvas.translate(getPaddingLeft(), getPaddingTop());
            textLayout.draw(canvas);
        }
        canvas.restore();
    }
}

此代码仅用于测试其是否正常工作且效率不高。哪个部分出错并导致它无法呈现文字?

1 个答案:

答案 0 :(得分:0)

你应该覆盖onMeasure并设置视图宽度/高度。您的示例代码将导致默认宽度/高度(可能为0)。