简体   繁体   中英

Load custom gifs from assets folder into recyclerview android

I have created a subfolder named gifs in assets folder where I've added 5 gifs . I would like to display these gifs in a recyclerview but I have not been able to as the recyclerview is empty. I cant understand where am going wrong, please help me. Thanks in advance!

public class GifAdapter extends RecyclerView.Adapter < GifAdapter.GifViewHolder > {
    Context context;
    List<String> gifList;
    GifAdapterListener listener;

    public GifAdapter(Context context, GifAdapterListener listener) {
        this.context = context;
        this.gifList = loadGifs();
        this.listener = listener;
    }

    private List<String> loadGifs() {
        List<String> gifs = new ArrayList();
        gifs.add("a.gif");
        gifs.add("aa.gif");
        gifs.add("aaa.gif");
        gifs.add("aaaa.gif");
        gifs.add("aaaaa.gif");
        return gifs;
    }

    // more code

    // onBindViewHolder
    @Override public void onBindViewHolder(@NonNull GifViewHolder holder, int position) {

        try {
            InputStream inputStream = context.getAssets().open("gifs");
            byte[] bytes = IOUtils.toByteArray(inputStream);
            holder.gifView.setBytes(bytes); // gifView is GifImageView using felipecsl.gifimageview library
            holder.gifView.startAnimation();

        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    // my fragment oncreate

    @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_gif, container, false);

        recyclerGifs = view.findViewById(R.id.recyclerGifs);
        recyclerGifs.setHasFixedSize(true);
        recyclerGifs.setLayoutManager(new GridLayoutManager(getActivity(), 2));
        gifAdapter = new GifAdapter(getContext(), this);
        recyclerGifs.setAdapter(gifAdapter);


        return view;
    }
}

Make use of Glide and get gifs from assets like this:

private List<String> loadGifs() {
    List<String> gifs = new ArrayList();
    gifs.add("file:///android_asset/a.gif");
    gifs.add("file:///android_asset/aa.gif");
    gifs.add("file:///android_asset/aaa.gif");
    return gifs;
}

Then load:

 @Override
 public void onBindViewHolder(@NonNull GifViewHolder holder, int position) {
            Glide.with(this).asGif().load(gifs(position)).into(imageView);
 }

Simple example to load GIF:

ImageView imageView = (ImageView) findViewById(R.id.imageView);
Glide.with(this).asGif().load(R.raw.image_gif).into(imageView);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM