我动态创建了一个ViewPager:
private View createCarousel(Context context)
{
ViewPager pager = new ViewPager(context);
ArrayList<Drawable> drawables = new ArrayList<>();
String[] carouselImages = mDisplayedGame.getCarouselImages();
if (carouselImages != null) {
for (String s : carouselImages) {
drawables.add(ImageLoader.getInstance().getDrawable(s));
}
pager.setAdapter(new ImageAdapter(context, drawables));
pager.setCurrentItem(0);
}
return pager;
}
注意:carouselImages!= null始终且
ImageLoader
正常工作。
public class ImageAdapter extends PagerAdapter
{
Context context;
private ArrayList<Drawable> mDrawables;
public ImageAdapter(Context context, ArrayList<Drawable> drawables, float width)
{
this.context = context;
mDrawables = drawables;
}
@Override
public int getCount()
{
return mDrawables.size();
}
@Override
public float getPageWidth(int position)
{
return 1f;
}
@Override
public boolean isViewFromObject(View view, Object object)
{
return view == ((ImageView) object);
}
@Override
public Object instantiateItem(ViewGroup container, int position)
{
ImageView imageView = new ImageView(context);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageView.setImageDrawable(mDrawables.get(position));
((ViewPager) container).addView(imageView, 0);
return imageView;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object)
{
((ViewPager) container).removeView((ImageView) object);
}
}
并添加到容器中:
mRootView.addView(createCarousel(this), new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
ViewPager没有显示。我做错了什么?
答案 0 :(得分:0)
对这种情况感到困惑,但这一行中出现了魔术:
mRootView.addView(createCarousel(this), new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
当我将高度改为100时:
mRootView.addView(createCarousel(this), new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 100 ));
内容出现在屏幕上。
设置布局参数时出现问题。
在我的情况下,我需要显示全屏图像,所以我只是在应用程序启动时计算尺寸,并将它们手动设置为构造函数参数。
答案 1 :(得分:0)
您是否忘记为儿童ImageView设置布局参数?尝试类似的事情怎么样:
ImageView imageView = new ImageView(context);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageView.setImageDrawable(mDrawables.get(position));
imageView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
((ViewPager) container).addView(imageView, 0);
return imageView;