嗯,这就是我认为的一种方法:
- 获取
EditText 宽度
- 获取文字宽度
首先,这里的代码并不完美,它允许用户放置超过宽度的部分(可能是因为EditText.getWidth() 将返回带有边框等的值。 ) 这只是提供一个想法。
关于这个方法的更多问题是,即使我们没有在 EditText 中显示文本,键盘缓冲区仍然会知道这一点,并且会给用户带来不好的影响,我尝试使用 InputFilter但结果是一样的(嗯,它有更多的错误)。
private int widthEditText;
// [...] in onCreate:
final EditText editText = (EditText) findViewById(R.id.text);
// p.s in onCreate the layout is not created yet, so i should wait to read the width
editText.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
widthEditText = editText.getWidth();
}
});
editText.addTextChangedListener(new TextWatcher() {
private String previousText;
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void afterTextChanged(Editable editable) {
Paint paint = editText.getPaint();
Rect rectangle = new Rect();
/* i used getTextBounds instead of measureText because it will return the float value but getWidth of
* edit text is a int. */
paint.getTextBounds(editable.toString(), 0, editable.length(), rectangle);
Log.d(TAG, "Text width: " + rectangle.width());
if (rectangle.width() > widthEditText) {
/* the user cannot type anymore */
Log.d(TAG, widthEditText + " > " + rectangle.width() + " blocked.");
editable.replace(0, editable.length(), previousText);
return;
}
previousText = editable.toString();
Log.d(TAG, "Continue to write, new previousText: " + previousText);
}
});
只是为了看看,我尝试使用 measureText 以返回浮点宽度(并使用比较 int 和 float)得到相同的结果:
@Override
public void afterTextChanged(Editable editable) {
Paint paint = editText.getPaint();
// Rect rectangle = new Rect();
/* i used getTextBounds instead of measureText because it will return the float value but getWidth of
* edit text is a int. */
// paint.getTextBounds(editable.toString(), 0, editable.length(), rectangle);
float width = paint.measureText(editable.toString());
Log.d(TAG, "Text width: " + width);
if (width > widthEditText) {
/* the user cannot type anymore */
Log.d(TAG, widthEditText + " > " + width + " blocked.");
editable.replace(0, editable.length(), previousText);
return;
}
previousText = editable.toString();
Log.d(TAG, "Continue to write, new previousText: " + previousText);
}
结果几乎一样......
我玩弄了android:ems="4",它应该提供字体大小(也许可以做一些事情来使它更适合?)但什么都没有(好吧不是,看起来看起来更好但我觉得它完全随机基于词)。
就我个人而言,我会避免这种情况,因为对我来说这听起来有点随机......也许存在一个我不知道的更好的方法......
我用三星 S4 设备测试过,所以我不知道它是否适用于其他设备!很抱歉,但 Genymotion 不起作用