dzboot02
dzboot02

Reputation: 2979

Extending TextView does not show text

I want to implement an OnLongClickListener to some of my TextViews, but I don't want to repeat the same code everywhere, so I want to extend TextView and implement the OnLongClickListener just once.

class LongClickToCopyTextView : TextView {

    constructor(context: Context) : this(context, null, 0)
    constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr)

    init {
        setOnLongClickListener {
            val clipboard = context?.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager?
            val clip = ClipData.newPlainText(context?.packageName, text)
            clipboard?.primaryClip = clip
            true
        }
    }
}

The implementation of the listener is used copy the text of the TextView into the clipboard when a user long presses it.

The problem is the text of the custom TextView is not shown. But if I use regular TextView the text is displayed correctly.

XML

<com.dzboot.myips.custom.LongClickToCopyTextView
     android:id="@+id/simNumber"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:textSize="14sp"
     android:text="00"
     app:layout_constraintEnd_toEndOf="parent"
     app:layout_constraintTop_toTopOf="parent" />

Upvotes: 0

Views: 178

Answers (1)

tynn
tynn

Reputation: 39863

The issue with setting default parameters for defStyleAttr is, that the base class might do the same to actually handle styles and states. Your initialisation happens in init {} anyhow.

class LongClickToCopyTextView : TextView {
    constructor(context: Context) : super(context)
    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr)

    init {
        setOnLongClickListener {
            val clipboard = context?.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager?
            val clip = ClipData.newPlainText(context?.packageName, text)
            clipboard?.primaryClip = clip
            true
        }
    }
}

Also you might want to extend fro AppCompatTextView instead. It has some newer features backported.

Upvotes: 1

Related Questions