Skip to content

Instantly share code, notes, and snippets.

@hector6872
Last active August 13, 2018 09:10
Show Gist options
  • Save hector6872/10d5d25cd4b3fbea39e3b39530266597 to your computer and use it in GitHub Desktop.
Save hector6872/10d5d25cd4b3fbea39e3b39530266597 to your computer and use it in GitHub Desktop.
AutoMaxLinesTextView for Android (Kotlin)
class AutoMaxLinesTextView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = android.R.attr.textViewStyle
) : AppCompatTextView(context, attrs, defStyleAttr) {
override fun onLayout(
changed: Boolean,
left: Int,
top: Int,
right: Int,
bottom: Int
) {
super.onLayout(changed, left, top, right, bottom)
if (movementMethod is ScrollingMovementMethod) return
val contentHeight = height - (paddingTop + paddingBottom)
if (gravity and Gravity.TOP == Gravity.TOP) {
for (line in lineCount - 1 downTo 0) {
if (layout.getLineBottom(line) < contentHeight) {
maxLines = line + 1
break
}
}
} else if (gravity and Gravity.BOTTOM == Gravity.BOTTOM) {
for (line in 0..lineCount) {
if (layout.getLineTop(line) > contentHeight) {
maxLines = line - 1
break
}
}
}
}
}
@hector6872
Copy link
Author

screenshot

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment