'EditText, How can control the cursor in TextWatcher?
I have a TextWatcher on an EditText, in the method afterTextChanged, I add characters to the EditText then I move the cursor to the end of EditText for continue adding text, but I have problems with that.
Like this:
public void afterTextChanged(Editable s) {
if(edittext.getText().length()==2){
// append dot to edittext
edittext.append(".");
// move cursor at end position in EditText
edittext.setSelection(edittext.getText().length());
}
}
In android 4.0v or superior, the cursor stay before the "." , and In 2.2v works fine, but in both I can't delete the characters.
Anyone with the same problem ?
Grettings
Solution 1:[1]
You can do something like this to avoid delete problem...
public class MainActivity extends Activity {
int count=0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText edittext=(EditText)findViewById(R.id.editText1);
edittext.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
}
@Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable ed) {
// TODO Auto-generated method stub
if(edittext.getText().length()==2 && count < 3){
// append dot to edittext
edittext.append(".");
// move cursor at end position in EditText
edittext.setSelection(edittext.getText().length());
}
count=edittext.getText().length();
}
});
}
Solution 2:[2]
Your code looks fine...
But, if you delete a character, text length is == 2 again and your code will automatically add a '.' char again - so it looks like deleting is not possible.
Solution 3:[3]
new TextWatcher() {
int startChanged,beforeChanged,countChanged;
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
startChanged = start;
beforeChanged = before;
countChanged = count;
}
public void afterTextChanged(Editable s) {
...your code here....
myEditText.setSelection(startChanged+countChanged);
...your code here...
}
}
};
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Arun C |
| Solution 2 | Jörn Buitink |
| Solution 3 | Stav Bodik |
