views:

44

answers:

1

I'm having difficulty getting my main View's onKey event to trigger. I'm not sure what I'm doing wrong, I have correctly implemented the onClick event but cannot seem to figure out the onKey event.

Here's the relevant code:

public class MyActivity extends Activity {
    private RelativeLayout main;
    private ApplicationToolbar toolbar;

    public void onCreate(Bundle savedInstanceState) {
        ...
        this.main = (RelativeLayout) this.findViewById(R.id.main);
        this.toolbar = new ApplicationToolbar(this);

        //  toolbar is added to main later on in the code...

        this.main.setOnClickListener(mClickListener);
        this.main.setOnKeyListener(mKeyListener);
    }

    private OnClickListener mClickListener = new OnClickListener() {
        public void onClick(View v) {
            toolbar.setVisibility(View.VISIBLE);    // Works correctly.
        }
    };

    private OnKeyListener mKeyListener = new OnKeyListener() {
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            toolbar.setBackgroundColor(0xFF0000FF);    //  Does not work.
            return true;
        }
    };
}

In fact, no matter what code I put within mKeyListener it does not execute, which leads me to believe that the event itself is never being triggered, even when I pressed a bunch of keys on my physical keyboard (Motorola Droid, Android 2.1).

A: 

You can try overriding onKeyDown(int keyCode, KeyEvent event)

Check:

Macarse
Thanks, overriding the onKeyDown event works, and it is a viable workaround for my situation. Any idea why my method above does not function properly though?
celestialorb
@celestialorb: Perhaps you don't have any `RelativeLayout`'s child `onFocus` when you press a key. Try adding an `EditText` inside.
Macarse