android - TextInputEditText - CompoundDrawable 未居中
问题描述
我试图通过创建一个 TextDrawable 然后使用compoundDrawable
. 除了可绘制对象被剪裁到组件右侧之外,一切都进行得很好。这可能是什么原因造成的?到目前为止,我尝试更改字体大小,但这并没有什么区别……是可绘制的太宽还是什么?
字符串是"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)
推荐阅读
- java - crontab 未触发计划作业
- amazon-cloudfront - 具有自定义来源和相同域的 Cloudfront
- java - Kafka 流和窗口化以在时间窗口内保持计数
- html - HTML 页脚问题,div 背景没有完全占据
- java - 在图像前面添加 JTextArea
- c# - Xamarin Forms 将自定义控制器中的命令与 Prism 绑定
- python - 根据条件删除列表的元素
- react-native - 如何在 react native 中使用 mqtt 或在 react native 中使用 java 脚本客户端
- ios - SceneKit 变换值,它们是如何实现的?
- apache-spark - Spark 上的分布式 DBSCAN