Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting text across multiple TextViews/Fragments using ViewPager

I'm trying to split some text across multiple Fragments loaded into a ViewPager using the Android compatibility library. The idea is to have something akin to the Kindle app, where you are swiping across multiple pages of text.

Initially, my source of text is a string defined in strings.xml and I am using an algorithm to determine the height of the device screen, and then split this string accordingly into a number of items for the ViewPager. As you can't get the height of a TextView ahead of time, I am just using a percentage value to determine what to set the maximum size of the TextView to on each page (this seems a bit ugly).

Does this seem like a reasonable approach, or am I going about this all the wrong way?

like image 976
cockadoodledo Avatar asked Dec 01 '11 17:12

cockadoodledo


1 Answers

As you can't get the height of a TextView ahead of time

Well, that depends on what you mean by "ahead of time" (time == text processing?).

  • You can measure() your ViewPager/TextView once and use its getMeasuredHeight()/getMeasuredWidth() in your calculations
  • You can wait for ViewTreeObserver.OnGlobalLayoutListener.onGlobalLayout() and use the "standard" layout measurements for the very same thing
  • (Not recommended) you can use ("screen height" - "decorations height") / "text height (font + spacing)" to know how many text lines will fit in your TextView
  • Etc. etc.
like image 157
avimak Avatar answered Dec 03 '22 16:12

avimak