ViewPager and PagerAdapter, get Drawable



您好,我有一个绑定到自定义PagerAdapter的ViewPager

布局只有一个图像视图,我想通过按下按钮获得此图像视图的可绘制对象。我将此方法添加到 PagerAdapter 中:

public Drawable getDrawable() {
    return imageView.getDrawable();
}

活动中,单击按钮时,我执行以下命令:

((MyAdapter)(mViewPager.getAdapter())).getDrawable();

问题是我获得的是我想要的正向图像而不是当前图像。

如何解决这个问题?

public class MyAdapter extends PagerAdapter {
 private final ArrayList<Images> mImages;
 private Context context;
 private ImageView imageView;

public MyAdapter(Context context, ArrayList<Images> images) {
    this.context = context;
    mImages = images;
}
public Drawable getDrawable() {
    return imageView.getDrawable();
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
    imageView = (ImageView) view.findViewById(R.id.iv);
    final String image = mImages.get(position).getFilename();
    Context context = imageView.getContext();
    final int width = ImageGalleryUtils.getScreenWidth(context);
    if (!TextUtils.isEmpty(image)) {
        Picasso.with(imageView.getContext())
                .load(image)
                into(imageView); 
    } else {
        imageView.setImageDrawable(null);
    }
 return view;
}
@Override
public int getCount() {
    return mImages.size();
}
}

如何初始化适配器? 你传递一个图像视图的数组列表?您需要它才能根据位置获得正确的图像视图:

在您的活动中,您应该致电:

((MyAdapter)(mViewPager.getAdapter())).getDrawable(mViewPager.getCurrentItem());

因此,首先在初始化适配器时,请像这样传递数据集:

private ArrayList<ImageView> mImageViews = new ArrayList<>();
private ArrayList<Images> mImages;
public MyAdapter(Context context, ArrayList<Images> images) { 
    this.context = context;
    mImages = images; 
}

然后在每个项目初始化分配图像视图时,将引用复制到该位置的数组列表。

imageView = (ImageView) view.findViewById(R.id.iv);
final String image = mImages.get(position).getFilename();
Context context = imageView.getContext();
final int width = ImageGalleryUtils.getScreenWidth(context);
if (!TextUtils.isEmpty(image)){
    Picasso.with(imageView.getContext())
    .load(image)
    .into(imageView);
} else {
    imageView.setImageDrawable(null);
}
mImageViews.add(position, imageView);

因此,您可以在您的方法中访问它:

public Drawable getDrawable(int position) {
    return mImageViews.get(position).getDrawable();
}

最新更新