0

你好,我有一个ViewPager绑定到自定义PagerAdapterViewPager和PagerAdapter,得到Drawable

布局只有一个ImageView的,我希望得到这个的ImageView的绘制,在按下按钮。我加入这个方法的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(); 
} 
} 

回答

0

如何初始化适配器?你传递了一个imageviews数组列表?你需要这个才能得到正确的ImageView,基于位置:

在你的活动,你应该叫:

((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(); 
} 
+0

我传递对象的ArrayList,其中也有不ImageView的或可绘制,但图像的URL。 – helloimyourmind

+0

你能发表更多的代码吗?有太多的猜测从我的部分 – silva96

+0

我张贴了我的适配器@ silva96 – helloimyourmind

相关问题