Search code examples
androidonkeydown

Why the text of this TextView is not changed?


Firstly I have to say that I have been like 2 weeks researching on this, but didn´t found the answer to this...

I have a TextView, so which I want to do is to change its text with the keycode of any hardware keypress (yes, I know some of keypresses cannot be used)... The problem is that the text doest want to change... Anyone please help me to solve this problem.

Thanks a lot!!!

Code:

import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnKeyListener;
import android.widget.TextView;



public class keycodelistener extends Activity {

    private TextView txtcode;

    public void onCreate(Bundle savedInstanceState) {   
        super.onCreate(savedInstanceState);     
        setContentView(R.layout.keycodedialog);

        txtcode = (TextView)findViewById(R.id.keypresstext);

    }

    public boolean onKeyDown(View v, int keyCode, KeyEvent event) {
        txtcode.setText(String.valueOf(keyCode));
        return super.onKeyDown(keyCode, event);
    }
}

Finally, it worked with this thanks to @CFlex !!! last three lines must be:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
     //Log.e("","yeeeahhhh");
     txtcode.setText(String.valueOf(keyCode));
     return true;

}

Solution

  • You need to Override onKeyDown(keyCode, event) because onKeyDown(View v, int keyCode, KeyEvent event) does not exist. Doc here

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        /* do what you want */
    }
    

    Hope this was helpfull.