У меня есть 2 вопроса, которые я уже определил в части «Вопрос».
Как сделать бесконечный свиток в RecyclerView
?
Например, я создаю заголовок баннера, используя RecyclerView
в моем проекте. Я получаю 4 изображения из базы. Теперь я хочу, когда пользователь находится на последнем элементе. затем, если они снова попытаются провести пальцем справа налево, снова появляется 1-е изображение или элемент. означает бесконечное RecyclerView
. и я также хочу, чтобы моя Recyclerview
автопрокрутка по горизонтали напоминала ViewPager
. Вы можете увидеть пример приложения для Android Flipkart, если вы индиец.
Ниже мой код:
Класс адаптера:
public class HeaderSliderAdapter extends RecyclerView.Adapter<HeaderSliderAdapter.ViewHolder> {
public List<Banner> banners;
public Context context;
public HeaderSliderAdapter(Context context, List<Banner> banners) {
this.banners = banners;
this.context = context;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.home_header, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(final ViewHolder holder, final int pos) {
int position = pos % banners.size();
if (TextUtils.isEmpty(banners.get(pos).getmSliderImage())) {
holder.mSliderImageView.setImageResource(R.drawable.app_logo);
} else {
Picasso.with(context)
.load(banners.get(pos).getmSliderImage())
.fit()
.into(holder.mSliderImageView, new Callback() {
@Override
public void onSuccess() {
holder.mBackgroundImage.setVisibility(View.GONE);
}
@Override
public void onError() {
holder.mBackgroundImage.setVisibility(View.VISIBLE);
}
});
}
}
@Override
public int getItemCount() {
return banners.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public ImageView mSliderImageView,mBackgroundImage;
View mView;
public ViewHolder(View itemView) {
super(itemView);
mView = itemView;
mSliderImageView = mView.findViewById(R.id.mSliderImage);
mBackgroundImage = mView.findViewById(R.id.backgroundImage);
}
}
}
Java класс:
private RecyclerView recyclerViewHeaderSlider;
private HeaderSliderAdapter headerSliderAdapter;
private List<Banner> banners;
recyclerViewHeaderSlider = view.findViewById(R.id.bannerSlider);
SnapHelper snapHelper = new PagerSnapHelper();
snapHelper.attachToRecyclerView(recyclerViewHeaderSlider);
recyclerViewHeaderSlider.setHasFixedSize(true);
recyclerViewHeaderSlider.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false));
recyclerViewHeaderSlider.setAdapter(headerSliderAdapter);
mFirestore.collection("banner").orderBy("priority", Query.Direction.DESCENDING).addSnapshotListener(new EventListener<QuerySnapshot>() {
@Override
public void onEvent(@javax.annotation.Nullable QuerySnapshot documentSnapshots, @javax.annotation.Nullable FirebaseFirestoreException e) {
if (e != null) {
Log.d(TAG, "Error : " + e.getMessage());
}
assert documentSnapshots != null;
for (DocumentChange doc : documentSnapshots.getDocumentChanges()) {
if (doc.getType() == DocumentChange.Type.ADDED) {
String doc_id = doc.getDocument().getId();
Banner banner = doc.getDocument().toObject(Banner.class).withDocId(doc_id);
banners.add(doc.getNewIndex(), banner);
headerSliderAdapter.notifyDataSetChanged();
} else if (doc.getType() == DocumentChange.Type.MODIFIED) {
String docID = doc.getDocument().getId();
Banner changedModel = doc.getDocument().toObject(Banner.class).withDocId(docID);
if (doc.getOldIndex() == doc.getNewIndex()) {
// Item changed but remained in same position
banners.set(doc.getOldIndex(), changedModel);
headerSliderAdapter.notifyItemChanged(doc.getOldIndex());
} else {
// Item changed and changed position
banners.remove(doc.getOldIndex());
banners.add(doc.getNewIndex(), changedModel);
headerSliderAdapter.notifyItemMoved(doc.getOldIndex(), doc.getNewIndex());
}
} else if (doc.getType() == DocumentChange.Type.REMOVED) {
// remove
banners.remove(doc.getOldIndex());
headerSliderAdapter.notifyItemRemoved(doc.getOldIndex());
}
}
}
});
Мой второй вопрос
Как сделать RecyclerView
, например, когда пользователь пытается провести пальцем, проведите только от 3 до 4 элементов одновременно. в настоящее время, когда я пытаюсь провести пальцем по экрану, почти бесконечные предметы зависят от моей скорости. который я не хочу.
Класс адаптера:
public class CouponDealsAdapter extends RecyclerView.Adapter<CouponDealsAdapter.ViewHolder> {
public List<CouponDeal> couponDeals;
public Context context;
// private OnItemClicked onClick;
public CouponDealsAdapter(Context context, List<CouponDeal> couponDeals) {
this.couponDeals = couponDeals;
this.context = context;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.coupons_deal, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(CouponDealsAdapter.ViewHolder holder, final int position) {
if (TextUtils.isEmpty(couponDeals.get(position).getStore_name())) {
holder.store_name.setText("Not Available");
} else {
holder.store_name.setText(couponDeals.get(position).getStore_name());
}
if (TextUtils.isEmpty(couponDeals.get(position).getDeal_description())) {
holder.deal_description.setText("Not Available");
} else {
holder.deal_description.setText(couponDeals.get(position).getDeal_description());
}
if (TextUtils.isEmpty(couponDeals.get(position).getOffer_validity())) {
holder.offer_validity.setText("Not Available");
} else {
holder.offer_validity.setText(couponDeals.get(position).getOffer_validity());
}
if (TextUtils.isEmpty(couponDeals.get(position).getCoupon_code())) {
holder.coupon_code.setText("Not Available");
} else {
holder.coupon_code.setText(couponDeals.get(position).getCoupon_code());
}
holder.coupon_code.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ClipboardManager clipboard = (ClipboardManager) context.getSystemService(CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("label", couponDeals.get(position).getCoupon_code());
clipboard.setPrimaryClip(clip);
Toast.makeText(context, "Code Copied", TastyToast.LENGTH_SHORT).show();
}
});
holder.url.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Uri uri = Uri.parse(couponDeals.get(position).getUrl());
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
if (intent.resolveActivity(context.getPackageManager()) != null) {
v.getContext().startActivity(intent);
}
}
});
if (TextUtils.isEmpty(couponDeals.get(position).getStore_image())) {
holder.store_image.setImageResource(R.drawable.app_logo);
} else {
Picasso.with(context)
.load(couponDeals.get(position).getStore_image())
.into(holder.store_image);
}
}
@Override
public int getItemCount() {
return couponDeals.size();
}
// public void setOnClick(OnItemClicked onClick) {
// this.onClick = onClick;
// }
//
// public interface OnItemClicked {
// void onItemClick(int position);
// }
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView store_name;
public TextView deal_description;
public TextView offer_validity;
public ImageView store_image;
public Button url;
public TextView coupon_code;
View mView;
public ViewHolder(View itemView) {
super(itemView);
mView = itemView;
store_name = (TextView) mView.findViewById(R.id.couponDeals_storeName);
deal_description = (TextView) mView.findViewById(R.id.couponDeals_description);
offer_validity = (TextView) mView.findViewById(R.id.couponDeals_validity);
store_image = (ImageView) mView.findViewById(R.id.couponDeals_store_image);
url = (Button) mView.findViewById(R.id.couponDeals_url);
coupon_code = (TextView) mView.findViewById(R.id.couponDeals_code);
}
}
}
Java класс:
private RecyclerView recyclerViewCouponDeals;
private CouponDealsAdapter couponDealsAdapter;
private List<CouponDeal> couponDeals;
couponDeals = new ArrayList<>();
couponDealsAdapter = new CouponDealsAdapter(getContext(), couponDeals);
recyclerViewCouponDeals = (RecyclerView) view.findViewById(R.id.couponDeals_recycler_view);
recyclerViewCouponDeals.setHasFixedSize(true);
recyclerViewCouponDeals.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false));
recyclerViewCouponDeals.setAdapter(couponDealsAdapter);
mFirestore.collection("CouponDeals").orderBy("priority", Query.Direction.DESCENDING).addSnapshotListener(new EventListener<QuerySnapshot>() {
@Override
public void onEvent(@javax.annotation.Nullable QuerySnapshot documentSnapshots, @javax.annotation.Nullable FirebaseFirestoreException e) {
if (e != null) {
Log.d(TAG, "Error : " + e.getMessage());
}
assert documentSnapshots != null;
for (DocumentChange doc : documentSnapshots.getDocumentChanges()) {
if (doc.getType() == DocumentChange.Type.ADDED) {
String doc_id = doc.getDocument().getId();
CouponDeal couponDeal = doc.getDocument().toObject(CouponDeal.class).withDocId(doc_id);
couponDeals.add(doc.getNewIndex(), couponDeal);
couponDealsAdapter.notifyDataSetChanged();
} else if (doc.getType() == DocumentChange.Type.MODIFIED) {
String docID = doc.getDocument().getId();
CouponDeal changedModel = doc.getDocument().toObject(CouponDeal.class).withDocId(docID);
if (doc.getOldIndex() == doc.getNewIndex()) {
// Item changed but remained in same position
couponDeals.set(doc.getOldIndex(), changedModel);
couponDealsAdapter.notifyItemChanged(doc.getOldIndex());
} else {
// Item changed and changed position
couponDeals.remove(doc.getOldIndex());
couponDeals.add(doc.getNewIndex(), changedModel);
couponDealsAdapter.notifyItemMoved(doc.getOldIndex(), doc.getNewIndex());
}
} else if (doc.getType() == DocumentChange.Type.REMOVED) {
// remove
couponDeals.remove(doc.getOldIndex());
couponDealsAdapter.notifyItemRemoved(doc.getOldIndex());
}
}
}
});