要确定屏幕上的可见文本,请等待文本布局完成,然后使用:
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和跨接字符串:
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中文网其他相关文章!