Drawing StaticLayout not working correct

898 views Asked by At

I've implemented a View with a Text.Layout and I'm drawing it but I'm getting nothing. Here is my code

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();
    }
}

this code is just for testing if it's working or not and it's not efficient. Which part is wrong and causing it to not render text?

1

There are 1 answers

0
Siyamed On

you should override onMeasure and set the view width/height. your example code will result in default width/height (probably 0).