如果文本字符串小于屏幕大小,则使 textview 选取框
Posted
技术标签:
【中文标题】如果文本字符串小于屏幕大小,则使 textview 选取框【英文标题】:Make textview marquee if text string is smaller than screen size 【发布时间】:2021-08-14 18:24:47 【问题描述】:当 textview 文本为“小”时,textview 不会滚动,但当 textview 文本“较大且文本超出屏幕大小”时,它会滚动。 我也不希望我的文字在“小”时选框
XML 文本视图:
<TextView
android:id="@+id/tickler_message"
style="@style/AppTheme.MarqueeTextStyle"
android:layout_
android:layout_
tools:text="@string/placeholder_marquee_text"
android:ellipsize="marquee"
android:focusable="true"
android:focusableInTouchMode="true"
android:singleLine="true"
android:scrollHorizontally="true"
android:marqueeRepeatLimit="marquee_forever"/>
活动:
binding.ticklerMessage.text = ticklerPlainText
binding.ticklerMessage.isSelected = true
【问题讨论】:
【参考方案1】:我们需要用文本检查textview的宽度,
If it exceed screen width -> textview marquee text properties,
else -> animate textview from left to right.
创建动画tickler_translation.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate
android:duration="10000"
android:fromXDelta="100%"
android:fillEnabled = "true"
android:repeatCount="infinite"
android:repeatMode="restart"
android:toXDelta="0%" />
</set>
文本视图
<TextView
android:id="@+id/tickler_message"
style="@style/AppTheme.MarqueeTextStyle"
android:layout_
android:layout_
tools:text="@string/placeholder_marquee_text"
android:ellipsize="marquee"
android:focusable="true"
android:singleLine="true"
android:focusableInTouchMode="true"
android:scrollHorizontally="true"
android:marqueeRepeatLimit="marquee_forever"/>
活动中
if (textCanScroll(ticklerMessage, ticklerPlainText))
//Show Marquee text if text length is greater than screen width
ticklerMessage.text = ticklerPlainText
ticklerMessage.maxLength(ticklerPlainText.length)
ticklerMessage.isSelected = true
ticklerMessage.gravity = Gravity.CENTER
ticklerLayout.makeVisible()
else
//Animate text horizontally if length is lesser than screen width
val animation = AnimationUtils.loadAnimation(it, R.anim.tickler_translation)
ticklerMessage.startAnimation(animation)
ticklerMessage.text = ticklerPlainText
ticklerMessage.gravity = Gravity.START or Gravity.CENTER_VERTICAL
ticklerLayout.makeVisible()
private fun textCanScroll(textView: TextView, text: String): Boolean
try
val bounds = Rect()
val textPaint: Paint = textView.paint
textPaint.getTextBounds(text, 0, text.length, bounds)
val height: Int = bounds.height()
val width: Int = bounds.width()
if (activity != null)
val screenWidth = Resources.getSystem().displayMetrics.widthPixels
return width >= screenWidth
catch (exception: Exception)
return false
return false
【讨论】:
以上是关于如果文本字符串小于屏幕大小,则使 textview 选取框的主要内容,如果未能解决你的问题,请参考以下文章
如何在不同的屏幕尺寸和密度下保持 TextView 中的文本大小一致?