在VideoView中播放视频时,Android后退按钮无法正常工作

时间:2016-04-06 05:57:34

标签: android android-videoview back-button mediacontroller

在VideoView中播放视频时,

Android后退按钮无效。但它在播放视频之前有效。我正在为VideoView使用自定义MediaController。
我尝试使用 dispatchKeyEvent ,它无效。

使用VideoView的活动代码:

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);
当我删除上面的代码时,

后退按钮非常适用。

我在堆栈溢出中经历了以下问题,但没有解决我的问题
我试过的Stack Overflow链接:

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

1 个答案:

答案 0 :(得分:0)

在我的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);