How to set the part of the text view is clickable

后端 未结 20 988
无人共我
无人共我 2020-11-22 01:29

I have the text \"Android is a Software stack\". In this text i want to set the \"stack\" text is clickable. in the sense if you click on t

20条回答
  •  无人及你
    2020-11-22 02:16

    Kotlin Version of Phan Van Linh's answer.

    Please note it has some minor modifications.

    fun makeLinks(textView: TextView, links: Array, clickableSpans: Array) {
        val spannableString = SpannableString(textView.text)
    
        for (i in links.indices) {
            val clickableSpan = clickableSpans[i]
            val link = links[i]
    
            val startIndexOfLink = textView.text.indexOf(link)
    
            spannableString.setSpan(clickableSpan, startIndexOfLink, startIndexOfLink + link.length,
                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        }
    
        textView.movementMethod = LinkMovementMethod.getInstance()
        textView.setText(spannableString, TextView.BufferType.SPANNABLE)
    }
    
    fun setupClickableTextView() {
        val termsOfServicesClick = object : ClickableSpan() {
            override fun onClick(p0: View?) {
                Toast.makeText(applicationContext, "ToS clicked", Toast.LENGTH_SHORT).show()
            }
        }
    
        val privacyPolicyClick = object : ClickableSpan() {
            override fun onClick(p0: View?) {
                Toast.makeText(applicationContext, "PP clicked", Toast.LENGTH_SHORT).show()
            }
        }
    
        makeLinks(termsTextView, arrayOf("terms", "privacy policy"), arrayOf(termsOfServicesClick, privacyPolicyClick))
    }
    

提交回复
热议问题