如何调整文本字体大小以适合 textview

新手上路,请多包涵

android中有什么方法可以调整textview中的textsize以适应它占用的空间?

例如,我正在使用 TableLayout 并在每一行添加几个 TextView s。由于我不希望 TextView 包装文本,我宁愿看到它降低了内容的字体大小。

有任何想法吗?

我试过 measureText ,但由于我不知道列的大小,使用起来似乎很麻烦。这是我想将字体大小更改为适合的代码

TableRow row = new TableRow(this);
for (int i=0; i < ColumnNames.length; i++) {
    TextView textColumn = new TextView(this);
    textColumn.setText(ColumnNames[i]);
    textColumn.setPadding(0, 0, 1, 0);
    textColumn.setTextColor(getResources().getColor(R.drawable.text_default));
    row.addView(textColumn, new TableRow.LayoutParams());
}
table.addView(row, new TableLayout.LayoutParams());

原文由 rudas 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 412
1 个回答

在我的情况下,使用 app:autoSize 并不能解决所有情况,例如它不能防止断字

这就是我最终使用的,它会缩小文本的大小,这样多行就不会出现断字

/**
 * Resizes down the text size so that there are no word breaks
 */
class AutoFitTextView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : AppCompatTextView(context, attrs, defStyleAttr) {

    private val paint = Paint()
    private val bounds = Rect()

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        var shouldResize = false
        paint.typeface = typeface
        var textSize = textSize
        paint.textSize = textSize
        val biggestWord: String = text.split(" ").maxByOrNull { it.count() } ?: return

        // Set bounds equal to the biggest word bounds
        paint.getTextBounds(biggestWord, 0, biggestWord.length, bounds)

        // Iterate to reduce the text size so that it makes the biggest word fit the line
        while ((bounds.width() + paddingStart + paddingEnd + paint.fontSpacing) > measuredWidth) {
            textSize--
            paint.textSize = textSize
            paint.getTextBounds(biggestWord, 0, biggestWord.length, bounds)
            shouldResize = true
        }
        if (shouldResize) {
            setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize)
        }
    }
}

原文由 Mohamed Khaled 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题