How to make ellipsize predictable

Denis Vlasov
Aug 20, 2018

Whats’up! It blog about about cool android stuff. And here we go.

Today we look how to make ellipsize in TextView more predictable. You want to create a readable list with titles. Titles have to be single line. Then if title will long and device small — text will be ellipsi… (ellipsized) in some place. But as programmer you want to control this behavior.

Firstly you create something like this: TextView + singleline.

<?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:layout_height="wrap_content"
android:layout_margin="16dp"
android:orientation="horizontal">


<TextView
android:id="@+id/tvName"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:singleLine="true"
tools:text="DAVID GARRETT / ДЭВИД ГАРРЕТТ" />


<TextView
android:id="@+id/tvDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
tools:text="07/11/2018" />

<TextView
android:id="@+id/tvPrice"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:text="7000 ₽" />

</LinearLayout>

This solution have one disadvantage. Ellipsize looks unpredictable.

It looks not very good. We will improve it soon.

Let’s make control.

We want to detect current ellipsize status and make text smaller if text will ellipsized. We have short and full text. Full text shown by default. Small text visible if full text ellipsized.

Let’s create a custom view inherited from TextView.

class CustomEllipsizeTextView(context: Context, attr: AttributeSet) : TextView(context, attr) {

private var shortText: String = if (isInEditMode) "short text" else ""

// variables used in draw method
private var textWidth: Float = 0f
private var isFullVisible: Boolean = true
private var visibleText: String = ""

override fun draw(canvas: Canvas) {
// calculate text width
textWidth = paint.measureText(text.toString())
isFullVisible = textWidth <= measuredWidth

// select correct text
visibleText = if (isFullVisible) text.toString() else shortText

// set text
text = visibleText

super.draw(canvas)
}

fun setText(fullText: String, shortText: String) {
text = fullText
this.shortText = shortText
}

}
Look’s good! We make our behaviour more customisable.

Code sample available on Github:

https://github.com/VDenis/EllipsizeInRecyclerView

--

--