summaryrefslogtreecommitdiff
path: root/app/src/main/java/foundation/e/advancedprivacy/common/TextViewHelpers.kt
blob: f87834ab9c7ca7fc5f26d1e79433461a4d1628c2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/*
 * Copyright (C) 2022 E FOUNDATION
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

package foundation.e.advancedprivacy.common

import android.content.Context
import android.content.res.ColorStateList
import android.text.Spannable
import android.text.SpannableString
import android.text.style.DynamicDrawableSpan
import android.text.style.ImageSpan
import android.widget.TextView
import androidx.annotation.StringRes
import androidx.appcompat.content.res.AppCompatResources
import androidx.appcompat.widget.TooltipCompat
import foundation.e.advancedprivacy.R

fun setToolTipForAsterisk(
    textView: TextView,
    @StringRes textId: Int,
    @StringRes tooltipTextId: Int
) {
    textView.text = asteriskAsInfoIconSpannable(textView.context, textId, textView.textColors)
    TooltipCompat.setTooltipText(textView, textView.context.getString(tooltipTextId))

    textView.setOnClickListener { it.performLongClick() }
}

private fun asteriskAsInfoIconSpannable(
    context: Context,
    @StringRes textId: Int,
    tint: ColorStateList
): Spannable {
    val spannable = SpannableString(context.getString(textId))
    val index = spannable.lastIndexOf("*")
    if (index != -1) {
        AppCompatResources.getDrawable(context, R.drawable.ic_info_16dp)?.let {
            it.setTintList(tint)
            it.setBounds(0, 0, it.intrinsicWidth, it.intrinsicHeight)
            spannable.setSpan(
                ImageSpan(it, DynamicDrawableSpan.ALIGN_CENTER),
                index,
                index + 1,
                Spannable.SPAN_INCLUSIVE_INCLUSIVE
            )
        }
    }
    return spannable
}