【问题标题】:Android: how to measure whether textview having enough space to render textview contentAndroid:如何衡量textview是否有足够的空间来渲染textview内容
【发布时间】:2019-11-29 03:23:19
【问题描述】:
请查找布局
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="12345678901234567890"/>
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:text="12345678901234567890"/>
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:text="12345678901234567890"/>
截图:
我想要的是在 textview 中移动 textview 或在运行时添加新的 textview?但更重要的是如何衡量 textview 右侧是否有足够的空间来呈现我的内容。
【问题讨论】:
标签:
android
android-layout
textview
【解决方案1】:
titleTxt.post {
val lineCount = titleTxt.lineCount
if (lineCount > 1) {
// Already break in 2 lines, update the content
// Do whatever you want with your content here
val textBuilder = StringBuilder()
for (line in 0 until lineCount) {
val layout = titleTxt.layout
textBuilder.append(titleTxt.text.subSequence(layout.getLineStart(line), layout.getLineEnd(line)))
.append("\n")
}
titleTxt.text = textBuilder
// Here I lower my font size so the overall height is not too big
titleTxt.setTextSize(TypedValue.COMPLEX_UNIT_PX, resources.getDimensionPixelSize(R.dimen.font_large).toFloat())
}
}
这是我在项目中所做的:
- 我检查行数
- 如果超过 2 行,则 1 行中的空间不足以容纳您的内容。
使用
layout 实例获取您想要的任何行的子字符串。随心所欲地处理您的内容
【解决方案2】:
假设你的 wrapper layout 是一个 LinearLayout,你可以使用这段代码来确定水平方向是否有足够的空间:
wrapperLayout.post{
if(wrapperLayout.width > textView1.width + textView2.width + textView3.width) {
//the space is enougth to contain three textview
} else {
//the sapce is not enougth
}
}