要確定螢幕上的可見文本,請等待文字佈局完成,然後使用:
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); } });
目標:當最後一條可見線完全適合視圖的高度時打破新頁面。
Pagination 類別實作必要的邏輯:
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 ... } }
下面的範例將分頁套用到混合HTML 和Spanned 字串:
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); } }
考慮使用PagedTextView庫以更輕鬆地整合:
dependencies { implementation 'com.github.onikx:pagedtextview:0.1.3' }
<com.onik.pagedtextview.PagedTextView android:layout_width="match_parent" android:layout_height="match_parent" />
以上是Android中如何實現文字分頁?的詳細內容。更多資訊請關注PHP中文網其他相關文章!