Not sure if there is a better way, but I got it by checking what will happen if I set the maxLines to be higher, and see if after measuring it will still fit in the original maxLines.
If you want to also animate nicely from collapsed to expanded mode of the TextView, check out my solution here.
If not, here's my solution for this very specific question :
MainActivity.kt
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val expectedWidthOfTextView = resources.displayMetrics.widthPixels
val originalMaxLines = textView.maxLines
if (originalMaxLines < 0 || originalMaxLines == Integer.MAX_VALUE)
Log.d("AppLog", "already unbounded textView maxLines")
else {
textView.maxLines = originalMaxLines + 1
textView.measure(
View.MeasureSpec.makeMeasureSpec(expectedWidthOfTextView, View.MeasureSpec.AT_MOST),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
)
Log.d("AppLog", "lines:${textView.lineCount}/$originalMaxLines")
if (textView.lineCount <= originalMaxLines)
Log.d("AppLog", "fit in original maxLines")
else
Log.d("AppLog", "exceeded original maxLines")
textView.maxLines = originalMaxLines
}
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent" android:orientation="vertical" android:gravity="center"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView" android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp" android:background="#1100ff00"
android:ellipsize="end" android:maxLines="4"
android:paddingEnd="16dp" android:paddingStart="16dp"
android:textColor="#c1000000" android:textSize="14sp"
android:text="Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."/>
</LinearLayout>