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  * ```
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  * ```
10  *
11  * Unless required by applicable law or agreed to in writing, software distributed under the License
12  * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
13  * or implied. See the License for the specific language governing permissions and limitations under
14  * the License.
15  */
16 package com.android.healthconnect.controller.utils
17 
18 import android.graphics.Typeface
19 import android.text.SpannableString
20 import android.text.Spanned
21 import android.text.TextPaint
22 import android.text.method.LinkMovementMethod
23 import android.text.style.ClickableSpan
24 import android.text.style.StyleSpan
25 import android.view.View
26 import android.widget.TextView
27 import androidx.core.view.ViewCompat
28 
29 /**
30  * Underlines {@code textView} with {@code linkContent} content and attaches the {@code
31  * onClickListener}.
32  */
convertTextViewIntoLinknull33 fun convertTextViewIntoLink(
34     textView: TextView,
35     string: String?,
36     start: Int,
37     end: Int,
38     onClickListener: View.OnClickListener?
39 ) {
40     val clickableSpan: ClickableSpan =
41         object : ClickableSpan() {
42             override fun onClick(view: View) {
43                 onClickListener?.onClick(view)
44             }
45 
46             override fun updateDrawState(textPaint: TextPaint) {
47                 super.updateDrawState(textPaint)
48                 textPaint.isUnderlineText = true
49             }
50         }
51     val spannableString = SpannableString(string)
52     spannableString.setSpan(clickableSpan, start, end, Spanned.SPAN_EXCLUSIVE_INCLUSIVE)
53     textView.setText(spannableString)
54     textView.movementMethod = LinkMovementMethod.getInstance()
55     textView.isLongClickable = false
56     ViewCompat.enableAccessibleClickableSpanSupport(textView)
57 }
58 
59 /**
60  * Returns a {@link SpannableString} with the {@code appName} bolded.
61  */
boldAppNamenull62 fun boldAppName(appName: String?, fullText: String): SpannableString {
63     val spannableString = SpannableString(fullText)
64     appName?.let {
65         val start = fullText.indexOf(appName)
66         if (start != -1) {
67             val end = fullText.indexOf(appName) + appName.length
68             spannableString.setSpan(
69                 StyleSpan(Typeface.BOLD), start, end, Spanned.SPAN_EXCLUSIVE_INCLUSIVE)
70         }
71     }
72     return spannableString
73 }
74