tags:

views:

2196

answers:

2

I have a parent ScrollView with a child view. When the user presses the back button, I want the child view to handle the event. I have tried a couple of things but none of them seem to work. pressing the back button kill sthe activity.

public class GameScrollView extends ScrollView{

     public GameScrollView(Context context) {
          super(context);
     }
     @Override
     public boolean onInterceptTouchEvent (MotionEvent ev){
          return false;

     }
     @Override
     public boolean onKeyDown (int keyCode, KeyEvent event){
          return false;

     }
}

in the child view I have the following code

public class GameView extends View implements OnTouchListener, onKeyListener{

     public boolean onKey(View v, int keyCode, KeyEvent event){
          if(keyCode == KeyEvent.KEYCODE_BACK){
                    //do stuff
          }
          invalidate();
          return true;        
     }
}

In the ScrollView I have also tried overriding the dispatchKeyEvent method to return false, but that did not work either. What am I doing wrong here?

Thanks!

A: 
@Override 
public boolean onKeyDown(int i, KeyEvent event) {

      if (i == KeyEvent.KEYCODE_BACK) {
          return true;
        else {
          super.onKeyDown(i, event);
          return true;
        }
      }
      return false;
    }

Also, i think you'd have to intercept the keypress in your activity and not the View.

buster
if I intercept the key press in the activity, how would I send it to the view to be handled? The view needs to do some drawing based on the key press.Thanks.
Maulin
A: 

I figured it out. The reason this was not working was because the child view did not have focus. Setting the requestFocus() property in the constructor of the child view fixed the problem.

Maulin