// return touch coordinates to original reference frame for any child views
return intercepted;
} else {
return super.onInterceptTouchEvent(ev);
}
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
if (getCurrentItem() == 0 && getChildCount() == 0) {
return false;
}
if (isVertical) {
return super.onTouchEvent(swapXY(ev));
} else {
return super.onTouchEvent(ev);
}
}
}
3.2 ViewPager和Fragment
- 采用了ViewPager+FragmentStatePagerAdapter+Fragment来处理。为何选择使用FragmentStatePagerAdapter,主要是因为使用 FragmentStatePagerAdapter更省内存,但是销毁后新建也是需要时间的。一般情况下,如果你是用于ViewPager展示数量特别多的条目时,那么建议使用FragmentStatePagerAdapter。关于PagerAdapter的深度解析,可以我这篇文章:PagerAdapter深度解析和实践优化
- 在activity中的代码如下所示
private void initViewPager() {
List list = new ArrayList<>();
ArrayList fragments = new ArrayList<>();
for (int a = 0; a< DataProvider.VideoPlayerList.length ; a++){
Video video = new Video(DataProvider.VideoPlayerTitle[a],
10,"",DataProvider.VideoPlayerList[a]);
list.add(video);
fragments.add(VideoFragment.newInstant(DataProvider.VideoPlayerList[a]));
}
vp.setOffscreenPageLimit(1);
vp.setCurrentItem(0);
vp.setOrientation(DirectionalViewPager.VERTICAL);
FragmentManager supportFragmentManager = getSupportFragmentManager();
MyPagerAdapter myPagerAdapter = new MyPagerAdapter(fragments, supportFragmentManager);
vp.setAdapter(myPagerAdapter);
}
class MyPagerAdapter extends FragmentStatePagerAdapter{
private ArrayList list;
public MyPagerAdapter(ArrayList list , FragmentManager fm){
super(fm);
this.list = list;
}
@Override
public Fragment getItem(int i) {
return list.get(i);
}
@Override
public int getCount() {
return list!=null ? list.size() : 0;
}
}
- 那么在fragment中如何处理呢?关于视频播放器,这里可以看我封装的库,视频lib
public class VideoFragment extends Fragment{
public VideoPlayer videoPlayer;
private String url;
private int index;
@Override
public void onStop() {
super.onStop();
VideoPlayerManager.instance().releaseVideoPlayer();
}
public static Fragment newInstant(String url){
VideoFragment videoFragment = new VideoFragment();
Bundle bundle = new Bundle();
bundle.putString(“url”,url);
videoFragment.setArguments(bundle);
return videoFragment;
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle arguments = getArguments();
if (arguments != null) {
url = arguments.getString(“url”);
}
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater,
@Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_video, container, false);
return view;
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
videoPlayer = view.findViewById(R.id.video_player);
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Log.d(“初始化操作”,"------"+index++);
VideoPlayerController controller = new VideoPlay