Search code examples
javaandroidandroid-activitykeyeventonkeydown

Android - Adding a key listener to an activity programmatically


All I want to do is programatically add an onKeyDown listener to an existing activity. A little bit of context for what I want to do: I want to make a standalone function that handles click events that occur in a mediaplayer.

ie: Let's pretend I have this class.

public class Main extends Activity
{    
@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
            setContentView(R.layout.maingui);
    }

@Override
     public boolean onKeyDown(int keyCode, KeyEvent event) {
         switch (keyCode) {
             case KeyEvent.KEYCODE_MEDIA_FAST_FORWARD:
        }
        return false;
      }
}

What I would like to do is add a function that adds the onKeyDown Listener through programming.

ie:

    public class Main extends Activity
    {    
    @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
                setContentView(R.layout.maingui);

                createListener();
        }

}
public void createListener()
{
    @Override
         public boolean onKeyDown(int keyCode, KeyEvent event) {

             switch (keyCode) {
                 case KeyEvent.KEYCODE_MEDIA_FAST_FORWARD:
          }
            return false;
    }
}

This obviously doesn't work, but gives you a good idea of what I'm trying to do.

This is what I've tried which doesn't work.

    public class Main extends Activity
    {    
    @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
                setContentView(R.layout.maingui);

            MyKeyClickClass.createListener(this);
    }

}
  • Then Imagine this function in a MyKeyClickClass class

    public static void createListener(Activity act)
        {      
            View testing = act.getWindow().getDecorView().findViewById(android.R.id.content);
    
            testing.setOnKeyListener(new OnKeyListener(){
    
                @Override
                public boolean onKey(View v, int keyCode, KeyEvent event) {
                    // TODO Auto-generated method stub
    
                    String test = "Hi";
    
                    return false;
                }
            });
        }
    

Is this possibly to do? I'm not getting any response to key events doing it this way.

Cheers


Solution

  • If for whatever reason you can't just use onKeyDown, couldn't you just have onKeyDown pass its parameters to another function?

    If you create a myKeyListener class then you can do something like this.

     @Override
     public boolean onKeyDown(int keyCode, KeyEvent event) {
         myKeyListener.onKeyDown(keyCode, event);
     }