Android back button and MediaController

萝らか妹 提交于 2019-11-26 16:23:22

问题


I know how to take control of the back button. I have a VideoView embedded in a FrameLayout. My question is when the video pops up, the video controls are present for a few seconds. Hitting the back button while they are visible hides the video controls. Is there a way to ignore that function and do the next back action as if the video controls weren't visible?

The reason I ask is if I really do want to go back, I must hit the back button twice; once to hide the controls and second to actually go back


回答1:


Based on the source code, this should work:

  1. Extend MediaController (for the purposes of this answer, call it RonnieMediaController)
  2. Override dispatchKeyEvent() in RonnieMediaController
  3. Before chaining to the superclass, check for KeyEvent.KEYCODE_BACK, and if that is encountered, tell your activity to finish()
  4. Use RonnieMediaController instead of MediaController with your VideoView

Personally, I'd just leave it alone, as with this change your user cannot make a RonnieMediaController disappear on demand.




回答2:


You can simply write:

mVideoView.setMediaController(new MediaController(this){
        public boolean dispatchKeyEvent(KeyEvent event)
        {
            if (event.getKeyCode() == KeyEvent.KEYCODE_BACK)
                ((Activity) getContext()).finish();

            return super.dispatchKeyEvent(event);
        }
    });

No need to create new class.




回答3:


You can also have the Activity handle the event:

mVideoView.setMediaController(new MediaController(this){
    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK ) {
            if (event.getAction() == KeyEvent.ACTION_DOWN) {
                return true;
            } else if (event.getAction() == KeyEvent.ACTION_UP) {
                ((Activity) getContext()).onBackPressed();
                return true;
            }
        }
        return super.dispatchKeyEvent(event);
    }       
});

Then handle it in your Activity:

@Override
public void onBackPressed() {
    // clean up or send result here
    finish();
}


来源:https://stackoverflow.com/questions/6051825/android-back-button-and-mediacontroller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!