Maulin Maulin - 2 months ago 7
Android Question

Opening childview back from scrollview

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 kills the 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!

Answer

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.