Problem with back button in VideoView

后端 未结 5 484
感动是毒
感动是毒 2021-01-05 08:03

I am having difficulty getting the back button to actually finish my activity when pressed. I am running a very simple videoview, using a progressdialog to show loading dial

相关标签:
5条回答
  • 2021-01-05 08:28

    finish() doesn't kill your activity, it just signals to Android that it doesn't need to run the Activity anymore.

    I remember solving this by putting "return" in proper places.

    0 讨论(0)
  • 2021-01-05 08:32

    From CommansWare

    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.

    Here is the link to the original post.

    0 讨论(0)
  • 2021-01-05 08:36
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            System.exit(0);
        }
    
        return false;
    }
    
    0 讨论(0)
  • 2021-01-05 08:39

    You'll want to create a custom MediaController class and override the dispatchKeyEvent function to capture the back KeyEvent and tell the activity to finish.

    See Android back button and MediaController for more info.

    public class CustomMediaController extends MediaController {
        public CustomMediaController(Context context, AttributeSet attrs) {
            super(context, attrs);
        }
    
        public CustomMediaController(Context context, boolean useFastForward) {
            super(context, useFastForward);
        }
    
        public CustomMediaController(Context context) {
            super(context, true);
        }
    
        public boolean dispatchKeyEvent(KeyEvent event)
        {
            if (event.getKeyCode() == KeyEvent.KEYCODE_BACK)
                ((Activity) getContext()).finish();
    
            return super.dispatchKeyEvent(event);
        }
    }
    
    0 讨论(0)
  • 2021-01-05 08:46

    You can simply write: (No need to create new class for MediaController)

    mVideoView.setMediaController(new MediaController(this){
            public boolean dispatchKeyEvent(KeyEvent event)
            {
                if (event.getKeyCode() == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP)
                    ((Activity) getContext()).finish();
    
                return super.dispatchKeyEvent(event);
            }
        });
    
    0 讨论(0)
提交回复
热议问题