To ascertain the visible text on the screen, wait for text layout completion and then retrieve it using:
ViewTreeObserver vto = txtViewEx.getViewTreeObserver(); vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() { @Override public void onGlobalLayout() { ViewTreeObserver obs = txtViewEx.getViewTreeObserver(); obs.removeOnGlobalLayoutListener(this); height = txtViewEx.getHeight(); scrollY = txtViewEx.getScrollY(); Layout layout = txtViewEx.getLayout(); firstVisibleLineNumber = layout.getLineForVertical(scrollY); lastVisibleLineNumber = layout.getLineForVertical(height+scrollY); } });
Objective: Break new pages when the last visible line fully fits within the view's height.
The Pagination class implements the necessary logic:
public class Pagination { // Configuration parameters private boolean mIncludePad; private int mWidth; private int mHeight; private float mSpacingMult; private float mSpacingAdd; private CharSequence mText; private TextPaint mPaint; private List<CharSequence> mPages; public Pagination(CharSequence text, int pageW, int pageH, TextPaint paint, float spacingMult, float spacingAdd, boolean inclidePad) { // ... initialization ... layout(); } private void layout() { // ... perform layout and pagination ... } }
The sample below applies pagination to a mixed HTML and Spanned string:
public class PaginationActivity extends Activity { // ... code ... private Pagination mPagination; private CharSequence mText; private int mCurrentIndex = 0; @Override protected void onCreate(Bundle savedInstanceState) { // ... code ... mText = TextUtils.concat(htmlString, spanString); mTextView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { // ... code ... mPagination = new Pagination(mText, mTextView.getWidth(), mTextView.getHeight(), mTextView.getPaint(), mTextView.getLineSpacingMultiplier(), mTextView.getLineSpacingExtra(), mTextView.getIncludeFontPadding()); update(); }); } private void update() { final CharSequence text = mPagination.get(mCurrentIndex); if(text != null) mTextView.setText(text); } }
Consider the PagedTextView library for easier integration:
dependencies { implementation 'com.github.onikx:pagedtextview:0.1.3' }
<com.onik.pagedtextview.PagedTextView android:layout_width="match_parent" android:layout_height="match_parent" />
The above is the detailed content of How to Implement Text Pagination in Android?. For more information, please follow other related articles on the PHP Chinese website!