Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android EditText onKeyUp

Just started with android, want to figure out keyUp on edittext. I followed various tutorials on keyUp it works but only on pressing back button. I want it to work on type. Just like phonebook, as you type some event will be triggered.

My code:

    private EditText input;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_contacts);
        addKeyListener();
    }

    public void addKeyListener() {
        input = (EditText) findViewById(R.id.names);
        input.setOnKeyListener(new OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                Toast.makeText(Contacts.this,
                        input.getText() + " you have typed", Toast.LENGTH_SHORT)
                        .show();
                return true;

            }
        });

    }

Current code is only working on back button, if I press back button then the Toast comes.

like image 893
Niraj Chauhan Avatar asked Mar 21 '23 11:03

Niraj Chauhan


2 Answers

import android.text.TextWatcher;

. .

You can add a TextWatcher to your text field. In your case, this would look something like:

  EditText in = new EditText(this); 
  in.addTextChangedListener(new TextWatcher() { 
    public void onTextChanged(CharSequence cs, int s, int b, int c) { 
      Log.i("Key:", cs.toString()); 
    } 
    public void afterTextChanged(Editable editable) { } 
    public void beforeTextChanged(CharSequence cs, int i, int j, int 
k) { } 
  }); 

Best,

like image 146
Hussein mahyoub Avatar answered Mar 23 '23 01:03

Hussein mahyoub


Chack if user type on EditText, and onTextChanged you can use your trigger :) Hope its help:)

    EditText mTextPhoneNumber;

    mTextPhoneNumber = (EditText)findViewById(R.id.example);

        mTextPhoneNumber.addTextChangedListener(new TextWatcher() {
                            @Override
                            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                            }

                            @Override
                            public void onTextChanged(CharSequence s, int start, int before, int count) {
                              Log.d("LOGER" , s.length()+""); // show the count of the Text in the TextView                        

                            }

                            @Override
                            public void afterTextChanged(Editable s) {

                            }


});
like image 33
Omri Lugasi Avatar answered Mar 23 '23 02:03

Omri Lugasi