Opening childview back from scrollview
-
05-09-2019 - |
Question
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!
Solution 2
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.
OTHER TIPS
@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.