Reputation: 451
I'm creating e-Commerce application, and i wanna ask you when i click next button then RecyclerView move to right and show next item, and when i click previous button then RecyclerView move to left and show previous item?
Previous and Next Button outside RecyclerView :
Code :
private RecyclerView rcTopPicks;
private RecyclerView.Adapter adapter;
private LinearLayoutManager layoutManager;
private ImageView previousTopPicks, nextTopPicks;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home, container, false);
previousTopPicks = view.findViewById(R.id.btn_left_top_picks);
nextTopPicks = view.findViewById(R.id.btn_right_top_picks);
initView(view);
getTopPicksData();
return view;
}
private void initViews(View view) {
rcTopPicks = view.findViewById(R.id.rc_top_picks);
layoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false);
rcTopPicks.setLayoutManager(layoutManager);
}
private void getTopPicksData() {
// Code for get JSON
....................
adapter = new TopPicksAdapter(productList);
rcTopPicks.setAdapter(adapter);
// This button is not move to left and not showing 2 previous items
previousTopPicks.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
rcTopPicks.scrollToPosition(adapter.getItemCount() - 1);
}
});
// This button is not move to right and not showing 2 next items
nextTopPicks.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
rcTopPicks.scrollToPosition(adapter.getItemCount() + 1);
}
});
}
The question is how to scroll position of recyclerview to right when i click next button? and how to scroll position of recyclerview to left when i click previous button?
Upvotes: 0
Views: 3452
Reputation: 21
Next and previous button clicked, this code scroll to next/prev view from current position.
binding.btPrevImage.setOnClickListener{
val imageCurrentPosition= (binding.rvAllImage.layoutManager as LinearLayoutManager).findFirstVisibleItemPosition()
if(imageCurrentPosition>0){
binding.rvAllImage.smoothScrollToPosition(imageCurrentPosition-1)
}
}
binding.btNextImage.setOnClickListener{
val imageCurrentPosition= (binding.rvAllImage.layoutManager as LinearLayoutManager).findLastVisibleItemPosition()
if(imageCurrentPosition<productImageAdapter.itemCount-1){
binding.rvAllImage.smoothScrollToPosition(imageCurrentPosition+1)
}
}
Upvotes: 2
Reputation: 636
Try to scroll to position with the help of your layoutManager
and you can add something like this to your code.
int firstVisible = layoutManager.findFirstVisibleItemPosition() - 1;
int lastVisible = layoutManager.findLastVisibleItemPosition() + 1;
if(lastVisible <= adapter.getItemCount()){
layoutManager.scrollToPosition(lastVisible);
}
Upvotes: 0