Reputation: 209
I have an input field where the user has to enter his forename and his surname. Now I want to check whether there is a whitespace which is neither at the beginning nor at the end of the input. Only in this case, a button is enabled.
Checking the whitespace is easy:
private EditText input;
input = (EditText) findViewById(R.id.input);
if(input.getText().toString().contains(" ")) {
button.setEnabled(true);
}
But how can I make sure that the whitespace is not at the beginning or end of the input?
Thanks for your help
Upvotes: 2
Views: 3187
Reputation: 1
eingabe.addTextChangedListener(new TextWatcher(){
@Override
public void onTextChanged(CharSequence s,int start,int before,int count){ }
@Override
public void beforeTextChanged(CharSequence s,int start,int count,int after){ }
@Override
public void afterTextChanged(Editable s){
weiterFertig.setEnabled(
s.length()>0&&!s.toString().startsWith(" ")&&!s.toString().endsWith(" ")&&s.toString().contains(" ")
)
;
}
});
Upvotes: 0
Reputation: 515
Try this.
String input = textview.getText().toString();
if(input.subString(1,input.length()-1).contains(" "))
button.setEnabled(false);
else
button.setEnabled(true);
Upvotes: 0
Reputation: 2271
Try this:
EDITED
String str = input.getText().toString();
if (str.contains(" ") && (!str.startsWith(" ") && !str.endsWith(" ")) )
button.setEnabled(true);
Or
if ( !(Character.isWhitespace(str.charAt(0)) && Character.isWhitespace(str.charAt(str.length()-1)) ) )
button.setEnabled(true);
Also you can use a combination of trim()
and contains
:
if(str.trim().contains(" "))
button.setEnabled(true);
Upvotes: 5
Reputation: 1332
You need to do something like this
code
if(input.getText().toString().substring(0,1).contains(" "))
System.out.println("failed");
else if((input.getText().substring((input.getText().length() -1),(input.getText().toString().length())).contains(" ")))
System.out.println("failed");
else
System.out.println("success");
I hope this helps you
Upvotes: 0
Reputation: 4365
result = input.getText().toString();
if(result.subString(0,1) == " "){
...
}
if(result.substring(result.length() - 0) == " "{
...
}
I hope this helps
Upvotes: -1