2017-06-09 85 views
0

請幫忙,我有viewpager與片段,數據綁定到viewmodel。我需要使用setCurrentItem並添加viewpager的適配器(view或viewmodel-databinding)的功能?是否有必要爲每個viewpager的項目創建視圖模型? 感謝您的幫助。ViewPager MVVM,DataBinding Android

回答

0

我在創建圖庫應用時遇到了類似的問題。這可能不是你的情況,因爲你使用的模型,但也許我的答案會以某種方式幫助你。我有一個ViewPagerFragment類只使用viewpager在其中擴展布局。然後使用自定義適配器設置ViewPager,該適配器擴展了FragmentStatePagerAdapter。另外我有一個ImageFragment類,它激發了它自己的佈局,並將圖像設置爲imageView。所以我ViewPagerFragment類看起來是這樣的:

public class ViewPagerFragment extends Fragment { 

public int mPosition; 

public static final String KEY_IMAGE_INDEX = "IMAGE_INDEX"; 

@Nullable 
@Override 
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) { 
    View view = inflater.inflate(R.layout.fragment_viewpager, container, false); 
    ImageFragment fragment = new ImageFragment(); 
    Bundle bundle = new Bundle(); 
    bundle.putInt(KEY_IMAGE_INDEX, mPosition); // position of an image passed to the child 
    fragment.setArguments(bundle); 

    ViewPager viewPager = (ViewPager) view.findViewById(R.id.view_pager); 
    ImageAdapter adapter = new ImageAdapter(getChildFragmentManager()); 
    viewPager.setAdapter(adapter); 
    viewPager.setCurrentItem(mPosition); 

    return view; 
} 

ImageAdapter類:

public class ImageAdapter extends FragmentStatePagerAdapter { 

    public ImageAdapter(FragmentManager fm) { 
     super(fm); 
    } 

    @Override 
    public Fragment getItem(int position) { 
    ImageFragment fragment = new ImageFragment(); 
    return fragment.newInstance(position); 
    } 

    @Override 
    public int getCount() { 
    //get count 
    } 

} 

而且ImageFragment

public class ImageFragment extends Fragment{ 

public static final String KEY_IMAGE = "IMAGE_POSITION"; 

@Nullable 
@Override 
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { 
     View view = inflater.inflate(R.layout.fragment_image, container, false); 
     int i = getArguments().getInt(KEY_IMAGE); 

     ImageView imageView = (ImageView) view.findViewById(R.id.fullPhoto); 

     Fragment viewPagerFragment = getParentFragment();  // access parent methods, can also be done through interface 
     if(viewPagerFragment instanceof ViewPagerFragment){ 
      mImages = ((ViewPagerFragment) viewPagerFragment).getImages(); 
     } 

    // set the imageView 
    } 


    public ImageFragment newInstance(int position) { 
     ImageFragment fragment = new ImageFragment(); 
     Bundle bundle = new Bundle(); 
     bundle.putInt(KEY_IMAGE, position); 
     fragment.setArguments(bundle); 

     return fragment; 
    } 
} 

很抱歉,如果它不能幫助!

0

因此,我創建了ObservableField名單和curentItem(INT) http://prntscr.com/fi4nl9 http://prntscr.com/fi4o2x

但我認爲有一些問題,新聞列表,我不`噸知道有效的是如何連接的數據適配器。現在我只用來替換所有數據,但加載函數只能追加新聞數據(延遲加載)