I’m facing an issue related to the deprecation of the singleLine attribute in Android

45 Views Asked by At

Although singleLine has been deprecated for quite some time, I haven’t found a suitable replacement for certain effects. For instance, consider the following scenario:

    <TextView
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:ellipsize="end"
        android:singleLine="true"
        android:text="aaaaaaa\nbbbbbbb\ncccccc" />

I want a single-line text view that truncates text with ellipsis (...) at the end. Additionally, I need to replace newline characters (\n) with a style similar to a space. The desired effect is illustrated in the image below: img

Could you please guide me on how to achieve the same effect using other XML attributes? Note that I prefer a solution that doesn’t involve writing code, as that would defeat the original purpose.

2

There are 2 best solutions below

1
On

Why do you think singleine is deprecated? There's no such notice on the TextView documentation:https://developer.android.com/reference/android/widget/TextView#setSingleLine(boolean)

But ignoring that, if you want to do it without that field- you're going to have to write code. There's no other way to do that. The easiest way is to set a TextWatcher on the field and whenever a new string is set, replace all \n in the string with a space and append an elipse to the end if one doesn't already exist (use the elipse unicode character so they can't put things between the dots).

Of course you could make a custom TextView subclass that does all that, and put that view in your xml. If you go that route, rather than a TextWatcher, override setText and getText to do that (setText to adjust the string and call super.setText(), getText() to remove the elipse again)

0
On

I'm not sure also, android:singleLine="true" was deprecated or not.

  1. For similar effect to singleLine and end with dot(..) can be get by adding this two lines in TextView,

    android:maxLines="1"
    android:ellipsize="end"
    
  2. For second case, if you want to replace white space for every "\n" in your string, you can get this by manual setText easily. Like this,

    val originalString = "This is a\nmultiline\nstring."
    val stringWithoutNewlines = originalString.replace("\n", " ")
    textview.text = stringWithoutNewlines