Ahm*_*azy 14 android autosize android-edittext
Android最近添加了对基于视图大小和最小和最大文本大小调整TextViews文本大小的支持.
https://developer.android.com/guide/topics/ui/look-and-feel/autosizing-textview.html
不幸的是,它们不支持EditTexts,那么EditText还有其他选择吗?
我被困住了,EditText是TextView的子级,但是不支持autosize?
我已经通过某种技巧实现了这一目标。首先,我看到了TextView代码要在EditTextView上复制并实现为扩展(在Kotlin中),但是..有很多方法,因此最终我放弃了该选项。
我所做的是使用不可见的TextView(是的,我知道这是一个完整的技巧,对此不太满意,但Google应该为此感到羞愧)
这是我的XML
<TextView android:id="@+id/invisibleTextView"
android:layout_height="0dp"
android:layout_width="match_parent"
android:focusable="false"
app:autoSizeTextType="uniform"
app:autoSizeMinTextSize="@dimen/text_min"
app:autoSizeMaxTextSize="@dimen/text_max"
app:autoSizeStepGranularity="@dimen/text_step"
android:textAlignment="center"
app:layout_constraintLeft_toLeftOf="@id/main"
app:layout_constraintRight_toRightOf="@id/main"
app:layout_constraintTop_toBottomOf="@id/textCount"
app:layout_constraintBottom_toBottomOf="@id/main"
android:visibility="invisible"
tool:text="This is a Resizable Textview" />
<EditText android:id="@+id/resizableEditText"
android:layout_height="0dp"
android:layout_width="match_parent"
android:textAlignment="center"
app:layout_constraintLeft_toLeftOf="@id/main"
app:layout_constraintRight_toRightOf="@id/main"
app:layout_constraintTop_toBottomOf="@id/textCount"
app:layout_constraintBottom_toBottomOf="@id/main"
android:maxLength="@integer/max_text_length"
tool:text="This is a Resizable EditTextView" />
Run Code Online (Sandbox Code Playgroud)
注意:两个视图的宽度/高度必须相同,这一点很重要
然后在我的代码上,我使用此textview的自动计算功能在EditTextView上使用。
private fun setupAutoresize() {
invisibleTextView.setText("a", TextView.BufferType.EDITABLE) //calculate the right size for one character
resizableEditText.textSize = autosizeText(invisibleTextView.textSize)
resizableEditText.setHint(R.string.text_hint)
resizableEditText.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(editable: Editable?) {
resizableEditText.textSize = autosizeText(invisibleTextView.textSize)
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
textCount.text = currentCharacters.toString()
val text = if (s?.isEmpty() ?: true) getString(R.string.text_hint) else s.toString()
invisibleTextView.setText(text, TextView.BufferType.EDITABLE)
}
})
}
private fun autosizeText(size: Float): Float {
return size / (resources.displayMetrics.density + MARGIN_FACTOR /*0.2f*/)
}
Run Code Online (Sandbox Code Playgroud)
注意,要更改提示的大小,请使用此Android EditText提示大小。
我知道这是一个艰苦的解决方法,但是至少我们可以确定,即使对未来版本进行可调整大小的更改,此方法也将继续起作用,而专有或废弃的github库将失败。
我希望有一天,谷歌能听到我们的声音,并在孩子身上实现这一奇妙的功能,并且我们可以避免所有这些事情
希望这可以帮助
| 归档时间: |
|
| 查看次数: |
6183 次 |
| 最近记录: |