Vertical Label In Android And Show Text In Center With Dynamic Width

23 Views Asked by At

class VerticalTextViewNew(context: Context, attrs: AttributeSet) :
    AppCompatTextView(context, attrs) {

    private val topDown = gravity.let { g ->
        !(Gravity.isVertical(g) && g.and(Gravity.VERTICAL_GRAVITY_MASK) == Gravity.BOTTOM)
    }
    private val metrics = BoringLayout.Metrics()
    private var padLeft = 0
    private var padTop = 0

    private var layout1: Layout? = null

    override fun setText(text: CharSequence, type: BufferType) {
        super.setText(text, type)
        layout1 = null
    }

    private fun makeLayout(): Layout {
        if (layout1 == null) {
            metrics.width = height
            paint.color = currentTextColor
            paint.drawableState = drawableState
            layout1 = BoringLayout.make(
                text,
                paint,
                metrics.width,
                Layout.Alignment.ALIGN_NORMAL,
                2f,
                0f,
                metrics,
                false,
                TextUtils.TruncateAt.END,
                height - compoundPaddingLeft - compoundPaddingRight
            )
            padLeft = compoundPaddingLeft
            padTop = extendedPaddingTop
        }
        return layout1!!
    }

    override fun onDraw(c: Canvas) {
        //c.drawColor(0xffffff80); // TEST
        if (layout == null) return
        c.withSave {
            if (topDown) {
                val fm = paint.fontMetrics
                translate(textSize - (fm.bottom + fm.descent), 0f)
                rotate(90f)
            } else {
                translate(textSize, height.toFloat())
                rotate(-90f)
            }

            translate(padLeft.toFloat(), padTop.toFloat())
            rotation = 180f
            makeLayout().draw(this)
        }
    }
}
<com.actionlogger.utils.common_view.view.VerticalTextViewNew
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/tvLabel"
    style="@style/FontSmallMedium"
    android:layout_width="@dimen/margin_18dp"
    android:layout_height="match_parent"
    android:layout_gravity="center"
    android:gravity="center"
    android:maxLines="1"
    android:ellipsize="end"
    android:text="@string/text_idea"
    android:textColor="@color/colorWhite"
    android:background="@color/colorPrimary"
    android:textStyle="bold" />    
   

enter image description here

i need to set my text in center of my above layout. i check some suggestion to set Layout.Alignment.ALIGN_NORMAL to Layout.Alignment.CENTER but it not work when i set this one it now show my text.i need only show my text in center of the view with my dynamic width. what i change to set my text center of the screen.

0

There are 0 best solutions below