Android: Setting onClickListener to a Part of text in a TextView - Issue

前端 未结 7 2246
忘掉有多难
忘掉有多难 2021-01-03 23:57

I am trying to recognise hashtags in my TextView and make them clickable such that I can take the user to another View when they click on the Hashtag.

I managed to i

7条回答
  •  天命终不由人
    2021-01-04 00:43

    I had similar problem - I had to do sth on a part of text clicked, but string was created at runtime. Maybe it will help someone - in this solution we do not care about finding indexStart, indexEnd in whole text (what can be quite awful) etc.:

     val action1ClickedSpan = object : ClickableSpan() {
         override fun onClick(widget: View?) {
              presenter.action1Clicked()
         }
     }
    
     val possibleActionsHint = SpannableStringBuilder().apply {
         val action1Start = this.length
         append(getString(R.string.action1))
         val action2Start = this.length
    
         append(...)
         append(...) 
    
         val action2Start = this.length
         append(getString(R.string.action1))
         val action2End = this.length
    
         setSpan(action1ClickedSpan, action1Start, action1End, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
         setSpan(...)
     }
    
     this.possibleActionsTextView.apply {
         text = possibleActionsHint
         movementMethod = LinkMovementMethod.getInstance()
     }
    

提交回复
热议问题