您好,登錄后才能下訂單哦!
本篇內容主要講解“怎么利用Android仿微博正文鏈接交互效果”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學習“怎么利用Android仿微博正文鏈接交互效果”吧!
首先我們先分析一下鏈接的組成部分,可以肯定的是需要一個顯示的標題,我們可能會對這個標題在UI表現上做些處理(常見的是一個鏈接的標志和設置不同的顏色)來提示和吸引用戶的注意,另外還需要點擊時跳轉的鏈接,這條鏈接可以是內部也可以是外部(這就屬于業務的需求)。關于鏈接的匹配方式可能會有不同的方案,我們這里選擇了使用a標簽的匹配方式,也就是接口會把鏈接的數據以a標簽的形式給我們,客戶端來進行匹配數據,下邊我們簡單的舉一個例子,接口返回數據如下:
"你說的<a href="https://www.qq.com" rel="external nofollow" rel="external nofollow" >我是鏈接</a>11111<a href="https://www.baidu.com" rel="external nofollow" rel="external nofollow" >我也是鏈接</a>好開心啊,哈哈哈哈"
接下來我們對數據的處理:
/** * 匹配a標簽直接插入鏈接 */ suspend fun computeLenFilterLink(text: String, mContext: Context): SpannableStringBuilder = withContext(Dispatchers.Default) { var strings = SpannableStringBuilder(text) val pattern = "<a \s*href\s*=\s*(?:.*?)>(.*?)</a\s*>" val p = Pattern.compile(pattern) val matcher = p.matcher(strings) while (matcher.find()) { val str = matcher.group() val linkTitle = matcher.group(1) ?: "" //a標簽鏈接正則匹配 val patternUrlString = "\s*(?i)href\s*=\s*("([^"]*")|'[^']*'|([^'">\s]+))" val patternUrl = Pattern.compile( patternUrlString, Pattern.CASE_INSENSITIVE ) //鏈接url val matcherUrL = patternUrl.matcher(strings) var linkUrl = "" while (matcherUrL.find()) { linkUrl = matcherUrL.group() linkUrl = linkUrl.replace("href\s*=\s*(['|"]*)".toRegex(), "") linkUrl = linkUrl.replace("['|"]".toRegex(), "") linkUrl = linkUrl.trim { it <= ' ' } break } //設置顏色 val sb = SpannableString("#$linkTitle") sb.setSpan( ForegroundColorSpan( ContextCompat.getColor(mContext, R.color.link_color) ), 0, sb.length, Spanned.SPAN_INCLUSIVE_INCLUSIVE ) sb.setSpan( object : MyLinkClickSpan(mContext) { override fun onSpanClick(widget: View?) { //鏈接跳轉 Toast.makeText(mContext, "點擊鏈=$linkUrl", Toast.LENGTH_SHORT).show() } }, 0, sb.length, Spanned.SPAN_INCLUSIVE_INCLUSIVE ) val start = strings.indexOf(str) strings.delete(start, start + str.length) //插入鏈接 strings.insert(start, sb) } return@withContext strings }
這里我們是用正則匹配的方式取出鏈接的標題和跳轉鏈接,然后設置鏈接的標志和顏色替換原來的a標簽插入正文數據中。接下來就是設置顯示的數據:
val string = "你說的<a href="https://www.qq.com" rel="external nofollow" rel="external nofollow" >我是鏈接</a>11111<a href="https://www.baidu.com" rel="external nofollow" rel="external nofollow" >我也是鏈接</a>好開心啊,哈哈哈哈" lifecycleScope.launch { val contentString = LinkCheckHelper.computeLenFilterLink(string,this@MainActivity) tvLink.text = contentString }
參考微博的交互效果我們會發現當我們觸摸鏈接內容時其背景會由透明變為鏈接文字的顏色,手指抬起時又置回透明。細心的你肯定發現我們在剛才鏈接數據的插入時設置了MyLinkClickSpan做了對鏈接點擊的處理,那么背景顏色的改變就要在ClickSpan中的 updateDrawState(ds: TextPaint)方法中進行處理,代碼如下:
class MyLinkClickSpan(private val context: Context) : ClickableSpan(), IPressedSpan { private var isPressed = false abstract fun onSpanClick(widget: View?) override fun onClick(widget: View) { if (ViewCompat.isAttachedToWindow(widget)) { onSpanClick(widget) } } override fun setPressed(pressed: Boolean) { isPressed = pressed } override fun updateDrawState(ds: TextPaint) { if (isPressed) { ds.bgColor = ContextCompat.getColor(context, R.color.link_bg_color) } else { ds.bgColor = ContextCompat.getColor(context, android.R.color.transparent) } ds.isUnderlineText = false } }
我們發現背景顏色的變化是需要對手指按下和抬起分別進行處理,所以這時不可避免的我們就要對觸摸事件進行處理:
class LinkTextView(context: Context, attrs: AttributeSet?) : AppCompatTextView(context, attrs) { private var mPressedSpan: IPressedSpan? = null init { isFocusable = false isLongClickable = false // 有鏈接點擊需求不設置則點擊無效 movementMethod = MyLinkMovementMethod.instance highlightColor = Color.TRANSPARENT } override fun onTouchEvent(event: MotionEvent): Boolean { val text = text val spannable = Spannable.Factory.getInstance().newSpannable(text) if (event.action == MotionEvent.ACTION_DOWN) { //按下時記下clickSpan mPressedSpan = getPressedSpan(this, spannable, event) } return if (mPressedSpan != null) { //如果有clickSpan就走MyLinkMovementMethod的onTouchEvent MyLinkMovementMethod.instance.onTouchEvent(this, getText() as Spannable, event) } else { super.onTouchEvent(event) } } private fun getPressedSpan( textView: TextView, spannable: Spannable, event: MotionEvent ): IPressedSpan? { var mTouchSpan: IPressedSpan? = null var x = event.x.toInt() var y = event.y.toInt() x -= textView.totalPaddingLeft x += textView.scrollX y -= textView.totalPaddingTop y += textView.scrollY val layout = textView.layout val line = layout.getLineForVertical(y) try { var off = layout.getOffsetForHorizontal(line, x.toFloat()) if (x < layout.getLineLeft(line) || x > layout.getLineRight(line)) { // 實際上沒點到任何內容 off = -1 } val linkSpans = spannable.getSpans(off, off, IPressedSpan::class.java) if (!linkSpans.isNullOrEmpty()) { mTouchSpan = linkSpans[0] } return mTouchSpan } catch (e: IndexOutOfBoundsException) { Log.d(this.toString(), "getPressedSpan", e) } return null } }
class MyLinkMovementMethod : LinkMovementMethod() { override fun onTouchEvent(widget: TextView, buffer: Spannable, event: MotionEvent): Boolean { return (sHelper.onTouchEvent(widget, buffer, event)) } companion object { val instance: MyLinkMovementMethod get() { if (sInstance == null) { sInstance = MyLinkMovementMethod() } return sInstance as MyLinkMovementMethod } private var sInstance: MyLinkMovementMethod? = null private val sHelper = SpanClickHelper() } }
class SpanClickHelper { private var mPressedSpan: IPressedSpan? = null fun onTouchEvent( textView: TextView, spannable: Spannable, event: MotionEvent ): Boolean { return when (event.action) { MotionEvent.ACTION_DOWN -> { mPressedSpan = getPressedSpan(textView, spannable, event) if (mPressedSpan != null) { //手指按下 設置按下為true,修改對應的鏈接文字背景顏色 mPressedSpan!!.setPressed(true) //設置選中區域 Selection.setSelection( spannable, spannable.getSpanStart(mPressedSpan), spannable.getSpanEnd(mPressedSpan) ) } mPressedSpan != null } MotionEvent.ACTION_MOVE -> { val touchedSpan = getPressedSpan(textView, spannable, event) if (mPressedSpan != null && touchedSpan != mPressedSpan) { //手指移動時 設置按下為false,對應的鏈接文字背景顏色置回透明 mPressedSpan!!.setPressed(false) mPressedSpan = null //移除選中區域 Selection.removeSelection(spannable) } mPressedSpan != null } MotionEvent.ACTION_UP -> { var touchSpanHint = false if (mPressedSpan != null) { touchSpanHint = true //手指抬起時 設置按下為false,對應的鏈接文字背景顏色置回透明 mPressedSpan!!.setPressed(false) //傳遞點擊事件回調 mPressedSpan!!.onClick(textView) } mPressedSpan = null Selection.removeSelection(spannable) touchSpanHint } else -> { if (mPressedSpan != null) { //其它收拾 都設置按下為false,對應的鏈接文字背景顏色置回透明 mPressedSpan!!.setPressed(false) } //移除選中區域 Selection.removeSelection(spannable) false } } } /** * 判斷手指是否點擊在鏈接上 */ private fun getPressedSpan( textView: TextView, spannable: Spannable, event: MotionEvent ): IPressedSpan? { var x = event.x.toInt() var y = event.y.toInt() x -= textView.totalPaddingLeft y -= textView.totalPaddingTop x += textView.scrollX y += textView.scrollY val layout = textView.layout val line = layout.getLineForVertical(y) try { var off = layout.getOffsetForHorizontal(line, x.toFloat()) if (x < layout.getLineLeft(line) || x > layout.getLineRight(line)) { // 實際上沒點到任何內容 off = -1 } val link = spannable.getSpans( off, off, IPressedSpan::class.java ) var touchedSpan: IPressedSpan? = null if (link.isNotEmpty()) { touchedSpan = link[0] } return touchedSpan } catch (e: IndexOutOfBoundsException) { Log.d(this.toString(), "getPressedSpan", e) } return null } }
代碼比較簡單,就是對點擊區域判斷是否為鏈接,然后根據手勢的操作分別設置給ClickSpan是否按下,來改變鏈接的背景顏色。
另外需要注意一點的是必須要調用下邊的代碼:
movementMethod = MyLinkMovementMethod.instance
此方法設置鏈接的點擊。 另外,不同的機型上系統會有一個鏈接的高亮顏色,我們需要調用
highlightColor = Color.TRANSPARENT
來取消掉。
這樣,鏈接的顯示和點擊交互就完成了。 具體效果:
到此,相信大家對“怎么利用Android仿微博正文鏈接交互效果”有了更深的了解,不妨來實際操作一番吧!這里是億速云網站,更多相關內容可以進入相關頻道進行查詢,關注我們,繼續學習!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。