Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent ' Enter key ' to trigger TextWatcher

I was making an application to act as remote keyboard where user will click on an edittext and type and corresponding alphabets will b typed in computer.

I have detected variaous alphabets and numbers with the help of TextWatcher and sent them to my server successfully.

Problem comes when user presses enter key. This also triggers TextWatcher . and since i am sending the latest entered changes , error shows up on server side.

As a solution what i did is , set one onkeylistener as well which will detect the enter key and perform action and CONSUME it , but unfortunately in that case also first textwatcher gets triggered and then onkeylistener.

Here is the code of my onkeylistener

 keyboard.setOnKeyListener(new OnKeyListener() {                 
  public boolean onKey(View v, int keyCode, KeyEvent event) {                   
    if(keyCode == KeyEvent.KEYCODE_ENTER&&event.getAction()==KeyEvent.ACTION_UP){  
                   out.println("enter");
                 return true;
              }
        return false;
            }
    });

Code of TextWatcher :

  private TextWatcher watcher = new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before, int count)    {
        if(count>0){
        out.println(":"+s.subSequence(start, start+count).toString());
        }
    }
            .
            .
            .

Problem is on pressing enter key it fires TextWatcher's onTextChanged as well as onkeylistener. whereas i want only on key listener to fire. I want to fire Textwatcher only in case of alphabets , numbers , some symbols etc.

Also if you can suggest different approach for detecting and sending characters ( soft ) will be great .

like image 894
PrateekArora Avatar asked Oct 02 '12 07:10

PrateekArora


1 Answers

Ok i think i solved it. in Textwatcher add this if statement:

if(s.toString().substring(start).contains("\n"))

in that way if last key entered was 'enter' then it would go into this is and then u can perform whatever u want.

like image 144
PrateekArora Avatar answered Nov 12 '22 09:11

PrateekArora