简体   繁体   English

具有数据绑定的Android ViewPager / PagerAdapter和不执行活动视图的instantiateItem

[英]Android ViewPager/PagerAdapter with Data Binding and instantiateItem not executing active view

I am using Android data binding in a MVVM framework. 我在MVVM框架中使用Android数据绑定。 I have a ViewPager setup with a corresponding PagerAdapter. 我有一个ViewPager设置与相应的PagerAdapter。 Some of the pages may contain videos. 某些页面可能包含视频。 The issue that I am having is that the instantiateItem method in the PagerAdapter always executes the next view in the PagerAdapter instead of the current view. 我遇到的问题是PagerAdapter中的instantiateItem方法总是执行PagerAdapter中的下一个视图而不是当前视图。 For example say page 1 has no video, but page 2 does. 例如,第1页没有视频,但第2页没有。 When the user views page 1, the video in page 2 starts playing. 当用户查看第1页时,第2页中的视频开始播放。 Here is the instantiateItem method: 这是instantiateItem方法:

     public Object instantiateItem(ViewGroup container, int position) {
    
        LayoutInflater layoutInflater = (LayoutInflater) getApplicationContext().getSystemService(Service.LAYOUT_INFLATER_SERVICE);
    

        ViewDataBinding binding = DataBindingUtil.inflate(layoutInflater, R.layout.main_layout, null, false);
    
        Post post = posts.get(position);
        myViewModel = new PostModel(post);
    
        binding.setVariable(BR.model, myViewModel);
  
        container.addView(binding.getRoot());
    

        return binding.getRoot();
    
    }

How can I make the instantiateItem execute the current view instead of the next view? 如何让instantiateItem执行当前视图而不是下一个视图? Is the issue related to setOffscreenPageLimit? 该问题是否与setOffscreenPageLimit有关?

You can't because it's main idea of ViewPager - it preload next N pages in order to make swiping smooth. 你不能,因为它是ViewPager的主要想法 - 它预加载下N个页面,以便顺利滑动。 Also actually you can setup it in order to see part of next view. 实际上,您也可以设置它以查看下一个视图的一部分。

I think you should use OnPageChangeListener , and manager start/stop of playing of your video when it needed here. 我认为您应该使用OnPageChangeListener ,并在此处需要时管理员开始/停止播放您的视频。

Btw, some advices - you can use that library in order to not write that boilerplate code at all. 顺便说一句,一些建议 - 您可以使用该 ,以便根本不编写样板代码。 Here my example of usage . 这是我的用法示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM