How to determine the number of lines visible in TextView?
android.text.Layout contains this information and more. Use textView.getLayout().getLineCount()
to obtain line count.
Be wary that getLayout()
might return null
if called before the layout process finishes. Call getLayout()
after onGlobalLayout()
or onPreDraw()
of ViewTreeObserver
. E.g.
textView.getViewTreeObserver().addOnPreDrawListener(() -> {
final int lineCount = textView.getLayout().getLineCount();
});
If you want only visible line count you should probably use the approach mentioned in the answer below:
Is there a way of retrieving a TextView's visible line count or range?
How to get line count of textview before rendering?
final Rect bounds = new Rect();
final Paint paint = new Paint();
paint.setTextSize(currentTextSize);
paint.getTextBounds(testString, 0, testString.length(), bounds);
Now divide the width of text with the width of your TextView to get the total number of lines.
final int numLines = (int) Math.ceil((float) bounds.width() / currentSize);
currentSize : Expected size of the view in which the text will be rendered. The size should not go beyond the screen width.
How to Check the number of lines in a String in Android?
Use a thread to count the number of lines,
textView.setText("Text Here");
textView.post(new Runnable() {
@Override
public void run() {
Log.v("Line count: ", textView.getLineCount()+"");
}
});
If you want to limit the number of lines in TextView from xml then use android:maxLines
Android TextView and getting line of text
If I understand correctly the answer to question 2 is:
textView.getLineBounds (int line, Rect bounds)
The width in pixels should be abs(bounds.right - bounds.left)
; and the height is abs(bounds.bottom - bounds.top)
Your first question is a bit more tricky, but something like this should do the required magic:
Layout layout = textView.getLayout();
String text = textView.getText().toString();
int start=0;
int end;
for (int i=0; i<textView.getLineCount(); i++) {
end = layout.getLineEnd(i);
line[i] = text.substring(start,end);
start = end;
}
Related Topics
Send Post Request with Params Using Retrofit
Which Can Replace Capturepicture Function
Android Datepicker Min Max Date Before API Level 11
Getactionbar() Returns Null (Appcompat-V7 21)
Android: Volley Http Request Custom Header
Streaming Audio from a Url in Android Using Mediaplayer
How to Add External Fonts to Android Application
How to Import Eclipse Project to Android Studio
Livedata Prevent Receive the Last Value When Start Observing
Listen to Own Application Uninstall Event on Android
Listening for Action_Screen_Off
How to Get Contacts from Native Phonebook in Android