How can I populate an ImageSwitcher from a url list? (EDIT: Horizontal RecyclerView)

早过忘川 提交于 2019-12-13 05:31:43

问题


I have an object which includes a list of strings. These are urls to pictures and I'm using Picasso library to set in ImageView. I would like to set these images in an ImageSwitcher, and I dont know how to do it (I've done some researches before but no results). Thanks for helping guys !

EDIT : I finally chose a Horizontal RecyclerView to have a Gallery like, so in my layout for a row there's only an ImageView. I also have now a Recycler Adapter but i dont know if i have to include my list of strings in the adapter, or just handle the imageView and create dynamically an ImageView and add it to the recycler list in my java class.... Thanks for helping !


回答1:


Your Adapter should have a constructor in which you will pass the urls as a parameter to the Adapter. Your Adapter will look something like this:

public class ImageSwitcherAdapter extends RecyclerView.Adapter<ImageSwitcherAdapter.MyViewHolder> {

    private Context context;
    private List<String> urls;

    public ImageSwitcherAdapter(Context context, List<String> urls) {
        this.context = context;
        this.urls = urls;
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.your_row_layout, parent, false);
        return new MyViewHolder(view);
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        Uri uri = Uri.parse(urls.get(position));
        Picasso.with(context).load(uri).into(holder.image);
    }

    @Override
    public int getItemCount() {
        return urls.size();
    }

    public static class MyViewHolder extends RecyclerView.ViewHolder {
        private ImageView image;

        public MyViewHolder(View itemView) {
            super(itemView);
            image = itemView.findViewById(R.id.your_imageview);
        }
    }
}

And setting the Adapter to your RecyclerView will look something like this:

RecyclerView recyclerView = findViewById(R.id.your_recyclerview);

LinearLayoutManager layoutManager = new LinearLayoutManager(this);
layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
recyclerView.setLayoutManager(layoutManager);

ImageSwitcherAdapter adapter = new ImageSwitcherAdapter(this, urls);
recyclerView.setAdapter(adapter);


来源:https://stackoverflow.com/questions/36309353/how-can-i-populate-an-imageswitcher-from-a-url-list-edit-horizontal-recyclerv

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!