【问题标题】:Android - EditText get physical length when type is passwordAndroid - 当类型为密码时,EditText 获取物理长度
【发布时间】:2017-09-29 20:21:43
【问题描述】:

我正在尝试获取 EditText 值的物理长度(以像素为单位),但是当它是密码时,我得到的是密码值的长度,而不是所有点的长度。

例如,我在编辑文本中输入了“Hello”,当我尝试获取它的长度时,它与做的相同:

paint.measureText("Hello");

但我想知道这个的长度
“密码:”是我添加的前缀,它不在 EditText 值本身中

如果有人可以帮助我,将不胜感激

【问题讨论】:

  • 那么,在您的示例中,您想返回“5”(点数)吗?
  • 好吧,我没有很好地解释自己,我想得到像素的长度:)
  • 长度(以像素为单位)是什么?整个编辑文本?第一个点的开始到最后一个点的结束?
  • 是的,你应该知道edittext.getText()方法中不会返回“密码:”

标签: android


【解决方案1】:

我猜密码 EditText 打印的实际字符将是 Unicode Bullet 字符之一。所以比如如果是U+2022,那么就可以使用。

StringBuilder sb = new StringBuilder();
int n = inputPassword.getText().length();
while (n-- > 0) sb.append('\u2022');

double width = inputPassword.getPaint()
        .measureText(sb.toString());

【讨论】:

  • 我想这就是我想要的,谢谢!但是您知道是否可以检测到 EditText 的最后一个字符何时变为点? :)
  • 遗憾的是,我不知道如何做到这一点。
  • @LeoAso 那真是个聪明人!
  • @Journey 我刚刚尝试过,但即使我更改了值,应用程序等待隐藏文本的时间也保持不变。而且我真的不想改变隐藏的时间,只是检测它什么时候发生
【解决方案2】:

使用

Rect bounds = new Rect(); 
Paint textPaint = edittext.getPaint(); 
textPaint.getTextBounds(edittext.getText().toString(), 
0,edittext.getText().length(), bounds); 
int height = bounds.height();
int width = bounds.width(); Toast.makeText(LoginActivity.this, ""+width, 
Toast.LENGTH_SHORT).show();

【讨论】:

  • 我不想要字符数,而是像素宽度
  • 矩形边界 = new Rect();绘制 textPaint = edittext.getPaint(); textPaint.getTextBounds(edittext.getText().toString(), 0,edittext.getText().length(), bounds); int 高度 = bounds.height(); int 宽度 = bounds.width(); Toast.makeText(LoginActivity.this, ""+width, Toast.LENGTH_SHORT).show();
【解决方案3】:

*不幸的是,它只返回绘制字体的长度而不是点。

content = editText.getText();
Rect bounds = new Rect();
Paint textPaint = editText.getPaint();
textPaint.getTextBounds(content, 0, content.length(), bounds);
int width = bounds.width();// This is the the length of the contents in pixels(painted).

希望对你有帮助。

【讨论】:

  • 我已经尝试过了,但它返回隐藏文本的像素长度,而不是点的长度:/
猜你喜欢
  • 2014-07-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-16
  • 1970-01-01
  • 1970-01-01
  • 2021-06-17
  • 1970-01-01
相关资源
最近更新 更多