D
D
DARKENN2019-10-28 17:48:55
Java
DARKENN, 2019-10-28 17:48:55

How to loop the slider from the recycler view so that the middle element (out of 3) is displayed first?

MainActivity

result = new ArrayList<>();

        slider = findViewById(R.id.slider);
        slider.setHasFixedSize(true);
        slider.setAdapter(adapter);
        slider.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        PagerSnapHelper snapHelper = new PagerSnapHelper();
        snapHelper.attachToRecyclerView(slider);

        adapter = new SliderAdapter(result);
        slider.setAdapter(adapter);

Adapter
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import java.util.List;

public class SliderAdapter extends RecyclerView.Adapter<SliderAdapter.SliderViewHolder> {

    private List<SliderModel> list;

    public SliderAdapter(List<SliderModel> list){
        this.list = list;
    }

    @Override
    public SliderAdapter.SliderViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
       return new SliderViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.slider_model, parent, false));
    }

    @Override
    public void onBindViewHolder(SliderViewHolder holder, int position) {

        SliderModel slider = list.get(position);
        holder.text.setText(slider.text);
        holder.image.setImageResource(R.drawable.ic_emoji_warn_72);
        holder.bgrd.setImageResource(R.drawable.menu_game);
    }

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

    class SliderViewHolder extends RecyclerView.ViewHolder{

        TextView text;
        ImageView image;
        ImageView bgrd;

        public SliderViewHolder(View itemView) {
            super(itemView);

            text = itemView.findViewById(R.id.text);
            image = itemView.findViewById(R.id.image);
            bgrd = itemView.findViewById(R.id.bgrd);
        }

    }
}

5db6ffc7ec75f816545600.jpeg

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Zagaevsky, 2019-10-28
@DARKENN

It is enough just to do this:
In the adapter

@Override
public int getItemCount() {
    return Integer.MAX_VALUE;
}

@Override
public void onBindViewHolder(SliderViewHolder holder, int position) {
      int realPosition = position % list.size();
      SliderModel slider = list.get(realPosition);
     ....

after initialization you do something like recyclerView.scrollToPosition(Integer.MAX_VALUE/2); //calculate that the position was what you need.
It is effectively looped. Scrolling to the end is impossible. And this is the easiest way.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question