Android back button and MediaController

后端 未结 4 1841
别那么骄傲
别那么骄傲 2020-12-03 03:09

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 contr

相关标签:
4条回答
  • 2020-12-03 03:15

    The previous solutions no longer work with Android Pie +, you must instead :

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            mediaController.addOnUnhandledKeyEventListener((v, event) -> {
                //Handle BACK button
                if (event.getKeyCode() == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP)
                {
                    mediaController.hide(); //Hide mediaController,according to your needs, you can also called here onBackPressed() or finish() 
                }
                return true;
            });
        }
    
    0 讨论(0)
  • 2020-12-03 03:26

    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();
    }
    
    0 讨论(0)
  • 2020-12-03 03:33

    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.

    0 讨论(0)
  • 2020-12-03 03:39

    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.

    0 讨论(0)
提交回复
热议问题