我有一个包含 VideoView 的简单布局。
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@color/black"
android:gravity="center" >
<VideoView
android:id="@+id/videoPlayer"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
</RelativeLayout>
使用Activity
此布局的创建一个Fragment
来启动 VideoView
public class VideoPlayerActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video_player);
createNewWorkerFragment();
}
private void createNewWorkerFragment() {
FragmentManager fragmentManager = getFragmentManager();
VideoPlayerActivityWorkerFragment workerFragment = (VideoPlayerActivityWorkerFragment)fragmentManager.findFragmentByTag(VideoPlayerActivityWorkerFragment.Name);
if (workerFragment == null) {
workerFragment = new VideoPlayerActivityWorkerFragment();
fragmentManager.beginTransaction()
.add(workerFragment, VideoPlayerActivityWorkerFragment.Name)
.commit();
}
}
}
VideoPlayerActivityWorkerFragment
如下:
public class VideoPlayerActivityWorkerFragment extends Fragment {
public static String Name = "VideoPlayerActivityWorker";
private VideoView mVideoPlayer;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
mVideoPlayer = (VideoView) mActivity.findViewById(R.id.videoPlayer);
mVideoPlayer.setVideoPath(mActivity.getIntent().getExtras().getString("path"));
MediaController controller = new MediaController(mActivity);
controller.setAnchorView(mVideoPlayer);
mVideoPlayer.setMediaController(controller);
mVideoPlayer.requestFocus();
mVideoPlayer.start();
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mActivity = activity;
}
@Override
public void onDetach() {
super.onDetach();
mActivity = null;
}
}
这是我遇到的问题,当VideoPlayerActivity
开始VideoPlayerActivityWorkerFragment
创建并VideoView
开始播放时,但是当我旋转设备时,视频停止并且不会播放,整个View
布局似乎都消失了。由于setRetainInstance(true);
我以为VideoView
会继续玩。有人可以让我知道我做错了什么吗?我在其他地方使用过这种模式(不是用 a VideoView
),它成功地允许旋转发生。
我不愿意使用android:configChanges="keyboardHidden|orientation|screenSize"
或类似的方法,我想用Fragment
s 处理方向变化。
预先感谢您的帮助。
编辑
我最终选择了我所做的解决方案,因为它有效。每次调用 onCreateView 时都需要重新创建 videoview 和控制器,并且需要在 onResume 中设置播放位置并在 onPause 中记录播放位置。但是,在旋转过程中播放是断断续续的。该解决方案不是最佳的,但它确实有效。