1 /**
2  * Copyright (C) 2022 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5  * in compliance with the License. You may obtain a copy of the License at
6  * ```
7  *      http://www.apache.org/licenses/LICENSE-2.0
8  * ```
9  * Unless required by applicable law or agreed to in writing, software distributed under the License
10  * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11  * or implied. See the License for the specific language governing permissions and limitations under
12  * the License.
13  */
14 package com.android.healthconnect.controller.utils
15 
16 import android.text.SpannableString
17 import android.text.Spanned
18 import android.text.TextPaint
19 import android.text.method.LinkMovementMethod
20 import android.text.style.ClickableSpan
21 import android.view.View
22 import android.widget.TextView
23 import androidx.core.view.ViewCompat
24 
25 /**
26  * Underlines {@code textView} with {@code linkContent} content and attaches the {@code
27  * onClickListener}.
28  */
convertTextViewIntoLinknull29 fun convertTextViewIntoLink(
30     textView: TextView,
31     string: String?,
32     start: Int,
33     end: Int,
34     onClickListener: View.OnClickListener
35 ) {
36     val clickableSpan: ClickableSpan =
37         object : ClickableSpan() {
38             override fun onClick(view: View) {
39                 onClickListener.onClick(view)
40             }
41 
42             override fun updateDrawState(textPaint: TextPaint) {
43                 super.updateDrawState(textPaint)
44                 textPaint.isUnderlineText = true
45             }
46         }
47     val spannableString = SpannableString(string)
48     spannableString.setSpan(clickableSpan, start, end, Spanned.SPAN_EXCLUSIVE_INCLUSIVE)
49     textView.setText(spannableString)
50     textView.movementMethod = LinkMovementMethod.getInstance()
51     textView.isLongClickable = false
52     ViewCompat.enableAccessibleClickableSpanSupport(textView)
53 }
54