Is there a way of retrieving a TextView's visible line count or range?

前端 未结 2 1068
无人及你
无人及你 2020-12-05 03:14

I have a full-screen TextView holding a long Spanned that requires scrolling. The TextView\'s getLineCount() gives me the total number of lines used for the entire block of

相关标签:
2条回答
  • 2020-12-05 03:49

    I figured out the answer:

    int height    = myTextView.getHeight();
    int scrollY   = myTextView.getScrollY();
    Layout layout = myTextView.getLayout();
    
    int firstVisibleLineNumber = layout.getLineForVertical(scrollY);
    int lastVisibleLineNumber  = layout.getLineForVertical(scrollY+height);
    
    0 讨论(0)
  • 2020-12-05 04:02

    To make them work you should write the code posted by @Robert in this way:

    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);
    
                }
            });
    
    0 讨论(0)
提交回复
热议问题