Replace String while enter into textfield in android
While entering String in EditText for example "Love Is Life" , after entering word "Love" enter space , then after if 开发者_开发知识库click the letter 'i' it automatically need to change it as Uppercase letter 'I' .
Which means the character after every Space of String need be in Uppercase and make the change dynamically while entering character in EditText to stimulate Camel case format.
If anyone knows means help me out.
Thanks.
You can add a TextWatcher to an EditText
and get notified each time the text is notified. Using that, you can just parse the String to find the characters after a space, and update them to uppercase.
Here's a quick test I made which works pretty well (far from optimal, because each time you edit the Editable it calls the listener again...).
editText.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable s) {
String string = s.toString();
int index = -1;
while (((index = string.indexOf(' ', index + 1)) != -1) && (index + 1 < string.length())) {
// Get character
char c = string.charAt(index + 1);
if (Character.isLowerCase(c)) {
// Replace in editable by uppercase version
s.replace(index+1, index + 2, Character.toString(c).toUpperCase());
}
}
}
});
To avoid being called to often, you could make all the changes in a char[]
and only commit to the Editable
if changes were made.
A simpler solution is probably to just use split(' ')
on your String, replace all first letters in the String[]
by the uppercase version (if needed), and commit only once to the Editable
.
A simpler optimisation would be to add a boolean to your anonymous class, set it to try when you enter afterTextChanged, set it back to false when you exit it, and only process the string if the boolean is false.
I know this is old, I stumbled upon it looking for the same sort of thing and found the perfect way to do it, so thought I'd share for anyone else who stumbles on this thread. You can set it in the layout XML for the EditText
using the android:inputType="textCapWords
<EditText
android:inputType="textCapWords" />
Doing that will cause the EditText
control to make every word start with a capital letter - including when the user changes it to lowercase them selves and moves on to the next word!
You need to implement a TextWatcher
for the field and listen to spaces , after a space you need to change the character the user entered to upper case
You can do it as, on key down function if etitText.getText.toString.trim.length-1 == '' set cha in caps later.
精彩评论