how can i create a custom view with a click in android?

Call setMovementMethod(LinkMovementMethod.getInstance()) on your custom view and it will open browser The onClick method is no longer needed as LinkMovementMethod will do all the work for you. Also, you can use UrlSpannable.

Here is your updated custom view. It no longer needs OnClickListener and Context no longer nullable type.

import android.content.Context
import android.text.SpannableString
import android.text.Spanned
import android.text.method.LinkMovementMethod
import android.text.style.URLSpan
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatTextView

class ContactUsLink : AppCompatTextView {
    constructor(context: Context, attrs: AttributeSet?, defStyle: Int) : super(
        context,
        attrs,
        defStyle
    ) {
        init()
    }

    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
        init()
    }

    constructor(context: Context) : super(context) {
        init()
    }

    private fun init() {
        val spannableString = SpannableString(text.toString())
        spannableString.setSpan(
            URLSpan("https://developer.android.com/reference/android/text/style/URLSpan?authuser=1"),
            0,
            text.length,
            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
        )
        text = spannableString
        movementMethod = LinkMovementMethod.getInstance()
    }

}

And here is your XML:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:background="@color/background_grey"
    android:orientation="vertical">

     
    <com.tesco.clubcardmobile.features.common.customview.ContactUsLink
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="12dp"
        android:text="Click. Here"
        android:layout_marginLeft="20dp"
        android:layout_marginTop="10dp"/>

</LinearLayout>

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top