How to set the part of the text view is clickable

后端 未结 20 1351
无人共我
无人共我 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:26

    The solutions provided are pretty decent. However, I generally use a more simple solution.

    Here is a linkify utility function

    /**
     * Method is used to Linkify words in a TextView
     *
     * @param textView TextView who's text you want to change
     * @param textToLink The text to turn into a link
     * @param url   The url you want to send the user to
     */
    fun linkify(textView: TextView, textToLink: String, url: String) {
        val pattern = Pattern.compile(textToLink)
        Linkify.addLinks(textView, pattern, url, { _, _, _ -> true })
        { _, _ -> "" }
    }
    

    Using this function is pretty simple. Here is an example

        // terms and privacy
        val tvTerms = findViewById(R.id.tv_terms)
        val tvPrivacy = findViewById(R.id.tv_privacy)
        Utils.linkify(tvTerms, resources.getString(R.string.terms),
                Constants.TERMS_URL)
        Utils.linkify(tvPrivacy, resources.getString(R.string.privacy),
                Constants.PRIVACY_URL)
    

提交回复
热议问题