سؤال

I'm making a ViewPager to display a series of images, which are identified by their position in an array of resource values. Here is my instantiateItem code for the adapter:

//indexes the images
@Override
public boolean isViewFromObject(View arg0, Object arg1) {
    return arg0.getTag().equals(arg1);
}

//serves the views
@Override
public Object instantiateItem(ViewGroup container, int position) {
    ImageView view = new ImageView(container.getContext());
    view.setScaleType(ScaleType.FIT_CENTER);
    view.setTag(position);
    view.setImageResource(mImages.get(position));
    container.addView(view, position);
    return view;
}

It doesn't display. Looking at container.getChildAt(0) confirms that the layout parameters are set to MATCH_PARENT but the width and height are 0. The container's own width and height are the screen dimensions (as expected).

Changing the code to

@Override
public Object instantiateItem(ViewGroup container, int position) {
    ImageView view = (ImageView) View.inflate(container.getContext(), R.layout.imageview, null);
    view.setScaleType(ScaleType.FIT_CENTER);
    view.setTag(position);
    view.setImageResource(mImages.get(position));
    container.addView(view, position);
    return view;
}

(where R.layout.imageview is just a layout with an ImageView in) didn't work. Setting the background colour to arbitrary visible values shows that the views are essentially not visible. What's going on?

هل كانت مفيدة؟

المحلول

The object returned should not be the View, but the object used to identify the View. In this case, the position is being used as an index, so the return value should be position:

@Override
public boolean isViewFromObject(View arg0, Object arg1) {
    return arg0.getTag().equals(arg1);
}

@Override
public Object instantiateItem(ViewGroup container, int position) {
    ImageView view = new ImageView(container.getContext());
    view.setScaleType(ScaleType.FIT_CENTER);
    view.setTag(position);
    view.setImageResource(mImages.get(position));
    container.addView(view, position);
    return position;
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top