N
N
Nikita2018-05-10 21:32:29
Android
Nikita, 2018-05-10 21:32:29

How to get width of textView from String(text)?

I have a string, is it possible to know the width of the textview? (the task is that I need to find out the size of the textView before it is created and not one method gives me its width, I want to know if it is possible to get it from the text)
My onDraw method, can someone tell me what prevents getting its width

public void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        @SuppressLint("DrawAllocation")
        Paint.FontMetrics fm = new Paint.FontMetrics();
        mTxtPaint.setColor(Color.RED);
        mTxtPaint.setTextSize(40.0f);

        mTxtPaint.getFontMetrics(fm);
        mTxtPaint.isAntiAlias();

        int margin = 5;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            canvas.drawRoundRect(90 - margin, 100 + fm.top - margin,
                                 115 + mTxtPaint.measureText(str) + margin, 100 + fm.bottom + margin,35,35, mTxtPaint);
        }
        mTxtPaint.setColor(Color.WHITE);
        canvas.drawText(str, 100, 100, mTxtPaint);

    }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
dimkss, 2018-05-11
@NeToster

I think you need to dance on the width of the text.
int widthOfText = fm.stringWidth(text);
https://stackoverflow.com/questions/258486/calcula...
https://stackoverflow.com/questions/18327825/how-d...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question