How to get line count of textview before rendering?

后端 未结 6 602
南笙
南笙 2020-12-02 20:29

How can I get the number of lines a string will take up in a TextView before it is rendered.

A ViewTreeObserver will not work because thos

6条回答
  •  情话喂你
    2020-12-02 20:37

    Reference: Getting height of text view before rendering to layout

    Get line of TextView before rendering.

    This is my code base the link above. It's working for me.

    private int widthMeasureSpec;
    private int heightMeasureSpec;
    private int heightOfEachLine;
    private int paddingFirstLine;
    private void calculateHeightOfEachLine() {
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        Display display = wm.getDefaultDisplay();
        Point size = new Point();
        display.getSize(size);
        int deviceWidth = size.x;
        widthMeasureSpec = View.MeasureSpec.makeMeasureSpec(deviceWidth, View.MeasureSpec.AT_MOST);
        heightMeasureSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        //1 line = 76; 2 lines = 76 + 66; 3 lines = 76 + 66 + 66
        //=> height of first line = 76 pixel; height of second line = third line =... n line = 66 pixel
        int heightOfFirstLine = getHeightOfTextView("A");
        int heightOfSecondLine = getHeightOfTextView("A\nA") - heightOfFirstLine;
        paddingFirstLine = heightOfFirstLine - heightOfSecondLine;
        heightOfEachLine = heightOfSecondLine;
    }
    
    private int getHeightOfTextView(String text) {
        // Getting height of text view before rendering to layout
        TextView textView = new TextView(context);
        textView.setPadding(10, 0, 10, 0);
        //textView.setTypeface(typeface);
        textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, context.getResources().getDimension(R.dimen.tv_size_14sp));
        textView.setText(text, TextView.BufferType.SPANNABLE);
        textView.measure(widthMeasureSpec, heightMeasureSpec);
        return textView.getMeasuredHeight();
    }
    
    private int getLineCountOfTextViewBeforeRendering(String text) {
        return (getHeightOfTextView(text) - paddingFirstLine) / heightOfEachLine;
    }
    

    Note: This code also must be set for real textview on screen

    textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, context.getResources().getDimension(R.dimen.tv_size_14sp));
    

提交回复
热议问题