Is there any easy way to make LinearLayoutManager to be as a circle (repetition items in a circle)?
I investigated it and found only way to make own custom LayoutManager, so it would be cool to find a way with less code
Is there any easy way to make LinearLayoutManager to be as a circle (repetition items in a circle)?
I investigated it and found only way to make own custom LayoutManager, so it would be cool to find a way with less code
First thing to do is change your adapter's getItemCount()
method to return Integer.MAX_VALUE
. This is not actually infinite, but it's over two billion so I doubt anyone's going to scroll that far.
Next, whenever you retrieve an item from your data source, don't just use position
. Instead, use position % dataSource.size()
... this will repeat your items as the user scrolls.
Here's an example:
public class MainActivity extends AppCompatActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RecyclerView recycler = (RecyclerView) findViewById(R.id.recycler);
recycler.setAdapter(new MyAdapter());
}
private static class MyAdapter extends RecyclerView.Adapter<MyViewHolder> {
private final List<String> items;
private MyAdapter() {
items = new ArrayList<>();
items.add("A");
items.add("B");
items.add("C");
items.add("D");
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View itemView = inflater.inflate(R.layout.itemview, parent, false);
return new MyViewHolder(itemView);
}
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
String item = items.get(position % items.size());
((TextView) holder.itemView).setText(item);
}
@Override
public int getItemCount() {
return Integer.MAX_VALUE;
}
}
private static class MyViewHolder extends RecyclerView.ViewHolder {
public MyViewHolder(View itemView) {
super(itemView);
}
}
}