Detect a new line in android text view
I am trying to create my first Android application in which it will help me do some outlining开发者_JS百科.
Quite simply I am trying to write some sort of detection that when a line starts with a hyphen, the next time there is a new line a hyphen will be placed in front of that new line.
I am looking for any pointers or directions for where I should be looking, as this is my first app.
Or in another sense what would be the best way to detect text being typed and change the EditText
based on it.
Since OnKeyListener does not work for Soft keyboard, I recommend using the TextWatcher.
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
if( -1 != charSequence.toString().indexOf("\n") ){
// Do your stuff
}
}
When you want to replace this sequence by some other string, try this:
public void afterTextChanged(Editable editable) {
int i = editable.toString().indexOf("\n");
if ( i != -1 ) {
editable.replace(i, i+1, "");
}
}
You could use the text watcher class of android which can be attached to a event.
EditText mPasswordLength = (EditText)findViewById(R.id.password_length);
mPasswordLength.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s){
}
public void beforeTextChanged(CharSequence s, int start, int count, int after){
}
public void onTextChanged(CharSequence s, int start, int before, int count){
}
});
The method you can use to edit the text is onTextChanged. More detailed description about when and why these events are fired is explained in this post.. Read the answer with max up votes.
You want an OnKeyListener
for the EditText
, then in the listener's onKey(View v, int keyCode, KeyEvent event)
method, see if it is the event
is KeyEvent.ACTION_DOWN
and the keyCode
is for KeyEvent.KEYCODE_ENTER
, if so then append a '-' to the end of the edittext.
精彩评论