在VideoView中播放视频时,Android后退按钮不起作用。但这在播放视频之前有效。我正在为VideoView使用自定义MediaController。我尝试使用 dispatchKeyEvent ,它不起作用。
正在使用VideoView的 Activity 代码:

mc = new CustomMediaController(mVideo.getContext(), screenIcon) {

@Override
public void hide(){
}

@Override
public boolean dispatchKeyEvent(KeyEvent event){
     if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
         super.hide();
         ((Activity) getContext()).finish();
         return true;
     }
     return super.dispatchKeyEvent(event);
}
};
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
   if ((keyCode == KeyEvent.KEYCODE_BACK)) {
     onBackPressed();
     finish();
   }
   return true;
}

@Override
public void onBackPressed() {
  super.onBackPressed();
  finish();
}

CustomMediaController还包含dispatchKeyEvent:
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
   if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
     ((Activity) getContext()).finish();
   }
   return super.dispatchKeyEvent(event);
}

另外,当我滚动布局时,mediaController不会在videoView中保持其位置。为解决此错误,我添加了一个代码来修复mediaController的位置。
FrameLayout f;
RelativeLayout.LayoutParams lp;
RelativeLayout.LayoutParams params;

         params = (RelativeLayout.LayoutParams) mVideo.getLayoutParams();
            params.height = mp.getVideoHeight();
            progress.dismiss();
            f = (FrameLayout) mc.getParent();
            lp = new RelativeLayout.LayoutParams(
                    RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
            lp.addRule(RelativeLayout.ALIGN_BOTTOM, mVideo.getId());
            try {
                ((LinearLayout) f.getParent()).removeView(f);
            } catch (Exception e) {
                ((RelativeLayout) f.getParent()).removeView(f);
            }
            ((RelativeLayout) mVideo.getParent()).addView(f, lp);
            //mc.setAnchorView(mVideo);
            mVideo.setLayoutParams(params);

当我删除上面的代码时,返回按钮非常有效。

我在堆栈溢出本身中经历了以下问题,但没有解决我的问题。
我尝试过的堆栈溢出链接:
Android back button and MediaController
Back button won't work when VideoView is playing video
First Back button press not caught when playing a video android
Problem with back button in VideoView

最佳答案

在我的mediacontroller中覆盖了dispatchKeyEvent()之后,它可以正常工作

 mediaController=new MediaController(this){
        @Override
        public void hide() {
            mediaController.show();
        }
        @Override
        public boolean dispatchKeyEvent(KeyEvent event){
            if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
                super.hide();
                ((Activity) getContext()).finish();
                return true;
            }
            return super.dispatchKeyEvent(event);
        }
    };

    videoView.setMediaController(mediaController);

10-05 17:47
查看更多