我目前正在做一个EditText,用户可以输入一行文字。但我有设置它的最大长度的问题。如果我将它设置为一个特定的数字,它变得非常不可预测,因为空间由于某种原因占用更多。所以我可以输入" asdnknfoisanfo"等,并获得我想要的正确长度,但是当你开始在单词之间输入空格时,长度变小,并且不会填充整个EditText。
SegFault
我要说的最终解决方案是将字符长度设置为EditText本身的长度。那么肯定,用户总是拥有正确的容量。这可能吗?或者我的问题有另一种解决方案吗?
答案 0 :(得分:1)
你可以试试这个。
String mStringStr = mEditText1.getText().toString().replaceAll("\\s", "");
现在你可以用字符串 mStringStr (没有空格)获得实际长度
mStringStr.length();
我希望这可以帮助你.. :)
答案 1 :(得分:0)
您可以使用以下代码
删除输入中的空格private void handleSignInResult(GoogleSignInResult result) {
Log.d(TAG, "handleSignInResult:" + result.isSuccess());
if (result.isSuccess()) {
// Signed in successfully, show authenticated UI.
GoogleSignInAccount acct = result.getSignInAccount();
Log.d(TAG, "authenticated " + acct.getDisplayName() + " " + acct.getEmail());
} else {
// Signed out, show unauthenticated UI.
Log.d(TAG, "unAuthenticated");
}
}
然后你可以使用
获取字符串的长度String input = Your_EditText.getText().toString();
input = input.replace(" ", "");
然后你可以检查输入是否正常
所以,整体代码应该是
int inputlength = input.length();
别忘了将这个观察者添加到你的editText
private final TextWatcher mywatcher = new TextWatcher() {
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
String input = Your_EditText.getText().toString();
input = input.replace(" ", "");
int inputlength = input.length();
if(inputlength>your_defined_length)
{
//do what you want to do
}
}
public void afterTextChanged(Editable s) {
}
};
答案 2 :(得分:0)
尝试使用此条件
if(findViewById(R.id.imageDescriptionTextEdit).getText().toString().trim().length() <= "your max length here"){
//Do something
}else{
//Show alert message
}
答案 3 :(得分:0)
您可以以编程方式尝试:
final EditText et = (EditText)findViewById(R.id.editText);
et.addTextChangedListener(new TextWatcher() {
int yourMaxLength = 10;
boolean canNotAddMore = false;
String maxText = "";
public void afterTextChanged(Editable s) {
if(canNotAddMore){
et.removeTextChangedListener(this);
et.setText(maxText);
et.addTextChangedListener(this);
}
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
String realCoontent = s.toString().trim().replace(" ", "");
if(realCoontent.length() >= yourMaxLength){
canNotAddMore = true;
maxText = s.toString();
}
}
public void onTextChanged(CharSequence s, int start, int before, int count) {}
});
}
此示例将从计算的字符列表中删除空格,以确定是否达到最大字符数。
例如,对于10个字符的限制,用户可以输入:
“1234567890”
或
“1 2 3 4 5 6 7 8 9 0”
答案 4 :(得分:0)
您可以使用Paint对象测量输入文本的宽度:
EditText input = findViewById(R.id.imageDescriptionTextEdit) // Your EditText
final Paint paint = input.getPaint();
float textWidth = paint.measureText(input.getText().toString());
if (textWidth > input.getWidth()) {
// Prevent further input.
}
您可以将此检查与TextWatcher结合使用。