我完成了制作从网址播放视频的视频播放器。唯一的问题是我使用ViewPager,其中不同的页面就是其中之一。所以问题是,如果我不使用 setUserVisibleHint(),则会出现两个问题:
现在我的代码是:
public class HomeFragment extends Fragment {
private VideoView mVideoView;
private ProgressBar mProgress;
private MediaController mMediaController;
private String url = null;
private Uri uri = null;
public HomeFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_home, container, false);
url = "xyz";
uri = Uri.parse(url);
mVideoView = (VideoView) view.findViewById(R.id.homeVideoView);
mVideoView.setBackgroundColor(Color.TRANSPARENT);
mProgress = (ProgressBar) view.findViewById(R.id.homeSpinner);
mProgress.setVisibility(View.VISIBLE);
mMediaController = new MediaController(getContext());
getActivity().getWindow().setFormat(PixelFormat.TRANSLUCENT);
loadVideos();
return view;
}
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if(isVisibleToUser){
//loading cart elements
}else{
Log.e("NOT", "VISIBLE");
}
}
//load the videos in the home fragment
private void loadVideos() {
try {
mVideoView.setMediaController(mMediaController);
mVideoView.setVideoURI(uri);
mVideoView.requestFocus();
mVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
public void onPrepared(final MediaPlayer mp) {
mp.start();
//handling the progressBar for buffering and ending it
mp.setOnInfoListener(new MediaPlayer.OnInfoListener() {
@Override
public boolean onInfo(MediaPlayer mediaPlayer, int i, int i1) {
if(MediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START == i){
mProgress.setVisibility(View.GONE);
mp.start();
}
if (MediaPlayer.MEDIA_INFO_BUFFERING_START == i){
mProgress.setVisibility(View.VISIBLE);
}
if(MediaPlayer.MEDIA_INFO_BUFFERING_END == i){
mProgress.setVisibility(View.GONE);
}
return false;
}
});
}
});
} catch (Exception e) {
Log.e("VIDEO PLAYER ERROR", e.getMessage());
}
}
}
我尝试过的是:
在我的isVisibleToUser案例中声明 loadVideo(),但是请说出这个问题,
VIDEO PLAYER EXCEPTION:无法将MedialController设置为空对象引用,并且progressBar无限加载。
从loadVideos()中移除所有内容并让 setOnPReparedListener()在那里,但这也给了我一个异常说
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.VideoView.setOnPreparedListener(android.media.MediaPlayer$OnPreparedListener)' on a null object reference
应用程序崩溃说mVideoView.stopPlayBack()在执行此操作后被调用null对象引用
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if(isVisibleToUser){
//loading cart elements
mVideoView.start();
}else{
Log.e("NOT", "VISIBLE");
mVideoView.stopPalyBack();
}
}
注意:此页面是应用程序打开时加载的第一个页面,因此在setUSerVisibleHint()
中页面实际可见性之前的某个时间条件会转到其他条件视频网址在视频视图中进行测试,因此只需处理viewPager内容。
经过多次努力,我恢复了原来的代码,经过长时间的研究,让大脑休息一下。上面的完整代码需要修改。任何建议将非常感谢!感谢