因此,我创建了一个通用的PageAdapter,可在应用程序的各个部分使用,如下所示:
public class ImagePagerAdapter extends PagerAdapter {
private final LayoutInflater layoutInflater;
private final Picasso picasso;
private final int layoutResId;
private final List<AssociatedMedia> images;
public ImagePagerAdapter(Context context, int layoutResId) {
layoutInflater = LayoutInflater.from(context);
picasso = Injector.getInstance().getPicasso();
this.layoutResId = layoutResId;
this.images = new ArrayList<>();
}
public void setMedia(List<AssociatedMedia> media) {
images.clear();
for (AssociatedMedia productMedia : media) {
if (productMedia.type == AssociatedMediaType.IMAGE) {
images.add(productMedia);
}
else {
// non-images all at the end
break;
}
}
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
AssociatedMedia image = images.get(position);
ImageView imageView = (ImageView) layoutInflater.inflate(layoutResId, container, false);
container.addView(imageView);
picasso.load(Uri.parse(image.urls[0])).into(imageView);
return imageView;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
ImageView imageView = (ImageView) object;
container.removeView(imageView);
picasso.cancelRequest(imageView);
}
@Override
public int getCount() {
return images.size();
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
}
然后,我在一个片段中称呼此适配器,如下所示:
ImagePagerAdapter productImageAdapter = new ImagePagerAdapter(getActivity(), R.layout.photo_container_small);
productImageAdapter.setMedia(medias);
productImage.setAdapter(productImageAdapter);
我的问题是,如何在片段中调用onClickListener。所以我的情况是,我们有一个图像轮播,一旦用户单击图像,它将在该图像上打开一个大视图,因此需要onItemClickListener,但这只能在pagerAdapter中调用。
因此,是否有一种方法可以在片段中调用onClickListener,或者在单击某个项目时从适配器通知片段?
最佳答案
这是对您的评论的回应。由于格式和大小的原因,我为此提供了一个答案。这是一个有关如何使用接口将片段与适配器类解耦的一般示例,该片段使适配器可以在多个片段(甚至其他项目)中重复使用。
public class MyAdapter {
MyAdapterListener listener;
private MyAdapter() {}
public MyAdapter(MyAdapterListener listeningActivityOrFragment) {
listener = listeningActivityOrFragment;
}
}
public interface MyAdapterListener {
void somethingTheFragmentNeedsToKnow(Object someData);
}
public class SomeFragment extends Fragment implements MyAdapterListener {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.my_view, container, false);
// Do everyhting here to init your view.
// Create an Adapter and bind it to this fragment
MyAdapter myAdapter = new MyAdapter(this);
return view;
}
// Implement the listener interface
@Override
public void somethingTheFragmentNeedsToKnow(Object someData) {
// Get the data and process it.
}
}
因此,根据您的情况,界面中的方法很可能是
onClick(int position);
。如果您需要多个方法,则只需添加它们即可。关于java - Android onClick自定义PagerAdapter,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33517029/