How to find android TextView number of characters per line?

后端 未结 3 2151
北海茫月
北海茫月 2020-12-01 05:26

So I have a TextView in android that has the width of the whole length of the screen and a padding of dip 5. How can I calculate the number of characters that will fit a si

3条回答
  •  执笔经年
    2020-12-01 06:17

    You can get total line of Textview and get string for each characters by below code.Then you can set style to each line whichever you want.

    I set first line bold.

    private void setLayoutListner( final TextView textView ) {
            textView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    textView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
    
                    final Layout layout = textView.getLayout();
    
                    // Loop over all the lines and do whatever you need with
                    // the width of the line
                    for (int i = 0; i < layout.getLineCount(); i++) {
                        int end = layout.getLineEnd(0);
                        SpannableString content = new SpannableString( textView.getText().toString() );
                        content.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 0, end, 0);
                        content.setSpan(new StyleSpan(android.graphics.Typeface.NORMAL), end, content.length(), 0);
                        textView.setText( content );
                    }
                }
            });
        }
    

    Try this way.You can apply multiple style this way.

提交回复
热议问题