【问题标题】:How Android EditText inputType attribute with value textMultiLine breaks the lines?具有值 textMultiLine 的 Android EditText inputType 属性如何打破界限?
【发布时间】:2017-09-18 21:01:52
【问题描述】:
我有一个 EditText 字段,属性 inputType 设置为 textMultiLine,这会将文本分成几行,到目前为止一切都很好。我在EditText 上附加了TextWatcher,这样我就可以检查是否有任何更改。在 afterTextChanged 方法中我想检查一行文本何时被分成 2 行,但是 textMultiLine 属性没有添加新的 line char,所以我的问题是:
如果没有换行符,我如何检查输入类型属性设置为 textMultiLine 的 EditText 中写入了多少行文本?
【问题讨论】:
标签:
android
android-layout
android-edittext
android-textwatcher
【解决方案1】:
无需使用Runnable 或发布到消息队列。只需在 afterTextChanged() 方法中调用 EditText.getLineCount():
final EditText editText = /* your EditText here */;
editText.addTextChangedListener(new TextWatcher() {
...
@Override
public void afterTextChanged(Editable editable) {
int numLines = editText.getLineCount();
// your code here
}
});
【解决方案2】:
试试这个:
editText.post(new Runnable() {
@Override
public void run() {
Log.d(TAG, "Line count: " + editText.getLineCount());
}
});
getLineCount() 将在editText 渲染完成时在 UI 线程上调用。