【问题标题】:How i create this textview style?我如何创建这种 textview 样式?
【发布时间】:2021-07-21 15:12:58
【问题描述】:

我尝试创建这种 textview 样式,我的问题是:

<TextView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:textStyle="bold"
            android:textSize="8dp"
            android:text="HOLLIDAY"
            android:textColor="@color/white"
            android:textAllCaps="true"
            android:gravity="center"
            android:rotation="90"
            android:singleLine="true"
            android:layout_gravity="bottom|center_vertical"
            />

我的输出是这样的:

image

我想要这个:

image

【问题讨论】:

  • 我认为你必须在每个字母后写一个带有 \n 的字符串。
  • @BhargavThanki 这个字符串可以由用户更改,所以这不是一个好的解决方案...... :(

标签: android xml textview


【解决方案1】:

您可以为此使用自定义文本视图

private const val VERTICAL_ROTATION = 270f

class VerticalTextView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyle: Int = 0) :
  AppCompatTextView(context, attrs, defStyle) {

  private var _measuredWidth: Int = 0
  private var _measuredHeight: Int = 0
  private val _bounds = Rect()

  override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec)
    _measuredHeight = measuredWidth
    _measuredWidth = measuredHeight
    setMeasuredDimension(_measuredWidth, _measuredHeight)
  }

  override fun onDraw(canvas: Canvas) {
    canvas.save()

    canvas.translate(_measuredWidth.toFloat(), _measuredHeight.toFloat())
    canvas.rotate(VERTICAL_ROTATION)

    val textPaint = paint
    textPaint.color = currentTextColor

    val text = getViewText()

    textPaint.getTextBounds(text, 0, text.length, _bounds)
    canvas.drawText(text, compoundPaddingLeft.toFloat(), ((_bounds.height() - _measuredWidth) / 2).toFloat(), textPaint)

    canvas.restore()
  }

  private fun getViewText(): String = super.getText().toString()
}

【讨论】:

  • 哦...需要代码...感谢回答的朋友!我们还没有关于 xml 的解决方案?
  • 不知道你可以试试
【解决方案2】:

如果你想用 XML 来做,你可以试试这个 hack。

  <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textStyle="bold"
        android:textSize="8sp"
        android:text="H\nO\nL\nI\nD\nA\nY"
        android:textColor="@color/white"
        android:textAllCaps="true"
        android:gravity="center"
        android:background="@color/colorAccent"
        android:layout_gravity="bottom|center_vertical"
        />

【讨论】:

    猜你喜欢
    • 2022-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-08
    • 1970-01-01
    • 1970-01-01
    • 2014-12-30
    • 2022-11-18
    相关资源
    最近更新 更多