我正在使用ViewPager輕掃一部分屏幕(而不是整個視圖/頁面)。Android ViewPager不會顯示第二頁?
我可以破解isViewFromObject只是返回true,然後我的第一個圖像出現,但我的第二個圖像將不會加載。有什麼想法,我在這裏失蹤?我在想我的isViewFromObject方法或實例化項目中的for循環有問題。
注意:有意不使用擴展FragmentStatePagerAdapter並擴展常規PagerAdapter。這是一個在instantiateItem上述執行
private class ScreenSlidePagerAdapter extends PagerAdapter {
public ScreenSlidePagerAdapter() {}
@Override
public Object instantiateItem (ViewGroup container, int position) {
LayoutInflater inflater = (LayoutInflater) container.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
int RLayoutId;
RLayoutId = R.layout.images_to_show; //an XML with just a LinearLayout
ViewGroup imageLayout = (ViewGroup) inflater.inflate(RLayoutId, null);
for (position = 0; position < mImageURLArraylist.size(); position++) {
container.addView(insertPhoto("http:" + mImageURLArraylist.get(position)));
}//end of for loop
return imageLayout;
}
@Override
public boolean isViewFromObject (View view, Object obj) { //Object parameter is received from instantiateItem(ViewGroup, int)
//loads the first image successfully if i just do return true.
//doesn't load any of my images when I do return view == ((View) obj);
}
//one of four methods that you must override when using pageradapters
@Override
public int getCount() {
//tested in debugging and this has the correct size (2)
return mImageURLArraylist.size(); //the number of pages the adapter will create.
}
@Override
public void destroyItem (ViewGroup container, int position, Object object) {
container.removeView((LinearLayout) object);
}//end of ScreenSlidePagerAdapter
我insertPhoto方法:
public View insertPhoto(String path){
LinearLayout layout = new LinearLayout(getActivity());
layout.setGravity(Gravity.CENTER);
ImageView imageView = new ImageView(getActivity());
imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
Picasso.with(getActivity()).load(path).into(imageView); //tried this but got errors when running > resize(layout.getWidth(), layout.getHeight()), also tried .fit() after .load image wouldn't load
layout.addView(imageView);
return layout;
}
工作正常!非常感謝Giso!愚蠢的後續問題,如果我可以,如果我將視圖添加到linearlayout我需要一個for循環。爲什麼我不在這裏/它是如何迭代所有的項目(即圖片)而沒有for循環? – Noobprogrammer
@Noobprogrammer:它沒有。 ViewPager的工作方式不同。實際上,它甚至不會立即加載所有頁面。相反,它只是實例化相鄰頁面,甚至將頁面進一步銷燬以節省內存。 可以使用[setOffscreenPageLimit()](http://developer.android.com/reference/android/support/v4/view/ViewPager.html#setOffscreenPageLimit%28int%29)來控制內存中保存的頁數。 –