我试图通过创建TextDrawable然后使用compoundDrawable
设置后缀来向我的TextInputEditText添加后缀。一切都进行得很顺利,除了drawable被剪切到组件右侧之外。是什么原因造成的?到目前为止,香港专业教育学院试图更改字体大小,但这没有任何区别。可绘制对象是否太宽?
字符串为"kr/månad"
,如您所见,它已被裁剪。
XML格式
<android.support.design.widget.TextInputLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/text_input_layout"
style="@style/TextInputLayoutStyle"
android:theme="@style/TextInputLayoutTheme">
<android.support.design.widget.TextInputEditText
android:id="@+id/text_input_edit_text"
style="@style/TextInputEditTextStyle" />
</android.support.design.widget.TextInputLayout>
组件代码
textInputEditText.setCompoundDrawables(null, null, TextDrawable(unitText), null)
文字可绘制
class TextDrawable(private val text: String?) : Drawable() {
private val paint: Paint
init {
paint = Paint()
paint.color = Color.BLACK
paint.textSize = 44f
paint.isAntiAlias = true
paint.isFakeBoldText = true
paint.typeface = Typeface.create("sans-serif-light", Typeface.NORMAL)
paint.style = Paint.Style.FILL
paint.textAlign = Paint.Align.CENTER
}
override fun draw(canvas: Canvas) {
text?.let { text ->
canvas.drawText(text, 0f, 0f, paint)
}
}
override fun setAlpha(alpha: Int) {
paint.alpha = alpha
}
override fun setColorFilter(cf: ColorFilter?) {
paint.colorFilter = cf
}
override fun getOpacity(): Int {
return PixelFormat.TRANSLUCENT
}
}
最佳答案
试试这个代码:
class TextDrawable(private val text: String?) : Drawable() {
private val paint = Paint().apply {
color = Color.BLACK
textSize = 44f
isAntiAlias = true
isFakeBoldText = true
typeface = Typeface.create("sans-serif-light", Typeface.NORMAL)
style = Paint.Style.FILL
setBounds(0, 0, measureText(text).toInt(), 0)
}
override fun draw(canvas: Canvas) {
text?.let { text ->
canvas.drawText(text, 0f, 0f, paint)
}
}
override fun setAlpha(alpha: Int) {
paint.alpha = alpha
}
override fun setColorFilter(cf: ColorFilter?) {
paint.colorFilter = cf
}
override fun getOpacity(): Int {
return PixelFormat.TRANSLUCENT
}
}
区别在于两行。我删除了这个
paint.textAlign = Paint.Align.CENTER
并添加以下内容:
setBounds(0, 0, measureText(text).toInt(), 0)
关于android - TextInputEditText-CompoundDrawable未居中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54361768/