当片段发生变化时,我想阻止videoView在viewPager中播放。代码中的问题是当我改变或进入下一个片段时视频仍在播放。
以下是Main Activity类的代码
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new FragmentStepOne(), "1");
adapter.addFragment(new FragmentStepTwo(), "2");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentStatePagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
@Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
@Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
这是Fragment类的代码
public class FragmentStepOne extends Fragment{
public FragmentStepOne() {
}
VideoView video;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_step_two, container, false);
video = (VideoView) rootView.findViewById(R.id.videoView);
Uri uri = Uri.parse("android.resource://"+ getActivity().getPackageName()+"/"+ R.raw.video);
video.setVideoURI(uri);
MediaController mc=new MediaController(getContext());
mc.setAnchorView(video);
video.setMediaController(mc);
video.requestFocus();
return rootView;
}
请提前帮助谢谢
答案 0 :(得分:0)
在您的片段中覆盖<div class="form-inline">
因为在override fun setUserVisibleHint(isVisibleToUser: Boolean)
之前调用了setUserVisibleHint
,所以请确保检查视图是否不为空(以便避免出现空指针异常)。
这是我实施我的方法:
onCreateView
我正在扩展片段override fun setUserVisibleHint(isVisibleToUser: Boolean) {
super.setUserVisibleHint(isVisibleToUser)
if (view != null)
if (!isVisibleToUser)
if (videoView.isPlaying) {
videoView.stopPlayback()
}
}