How do I determine how much text will fit in a TextView in Android?

若如初见. 提交于 2020-01-20 17:25:35

问题


I have a layout that looks something like this:

[TextView 1] [TextView 2]
[ TextView 2 spill-over ]

Essentially, I need the contents of TextView 2 to wrap to the next line, but start where TextView 1 starts. I was thinking that if I knew how much text would fit into TextView 2 before it runs out of space on line one, I could take the rest of the text and put it in another TextView below the first two. So I need to measure how much text will fit into a TextView (which can be tricky because as far as I can tell, Android will try to break the text in a TextView at a good location so that it won't break a word in the middle if it can be avoided) or I need a new idea on how to lay this out.

Any help would be greatly appreciated.

Thanks in advance,

groomsy


回答1:


Unfortunately, Paint.breakText didn't return the exact same result as in was seen in my two-line TextView.

However, this worked

int numChars = textView.getLayout().getLineEnd(1);

(use numberOfLines - 1 as the parameter to it)

Ref http://developer.android.com/reference/android/text/Layout.html#getLineEnd(int) Set individual lines of TextView to different width




回答2:


You can create a Paint object with TextView2's text size and use breakText() to measure how many characters will fit in your TextView2's width.

(This is untested code - might need some slight modifications)

String textToBeSplit = arbitraryText; // Text you want to split between TextViews
float textView2Width = somehowGetItsWidth; // TextView2's width
float myTextSize = textView2.getTextSize();

Paint paint = new Paint();
paint.setTextSize(myTextSize); // Your text size
int numChars = paint.breakText(textToBeSplit, true, float textView2Width, null);

numChars tells you how many characters in textToBeSplit will fit in TextView2's width, enabling you to split it between your views.




回答3:


You don't need two TextViews in order to do this, you should always use as few views as possible and you can use a spannable in order to have two styles for the same textview.
For example with :

TextView tv = (TextView) findViewById(R.id.textview);
SpannableString text = new SpannableString(myString);

text.setSpan(new TextAppearanceSpan(getContext(), R.style.myStyle), 0, 5, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
text.setSpan(new TextAppearanceSpan(getContext(), R.style.myNextStyle), 6, 10, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

tv.setText(text, TextView.BufferType.SPANNABLE);


来源:https://stackoverflow.com/questions/3409271/how-do-i-determine-how-much-text-will-fit-in-a-textview-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!