Recyclerview внутри Recyclerview, получить позицию щелчка дочерней строки внутри родительского адаптера
В моем проекте требование заключается в том, что в разделе "Активность" отображается список элементов, и я показываю дату в списке с ценой, что я хочу, чтобы пользователь выбрал дату, цвет даты изменится, и когда нажмите на элемент корзины, следует добавить на карту,
Проблема: я не могу получить дочернюю позицию recyclerView внутри родительского recyclerView onBindViewHolder
,
Есть ли способ получить положение дочерней строки (строки даты) внутри родительского reyclerview.
Ниже изображение, показывающее с тремя списками, и в каждом списке есть список строк дат. Когда пользователи нажимают на конкретную дату, я хочу, чтобы эта дата была в родительском классе recyclerView Adapter внутри onBindViewHolder.
Ниже приведены адаптеры:
Ниже класс родительского адаптера
FlowerListAdapter.java:
public class FlowerListAdapter extends RecyclerView.Adapter<FlowerListAdapter.MyViewHolder> {
ArrayList<FlowerListPojo> list;
Context context;
public FlowerListAdapter(Context context, ArrayList<FlowerListPojo> list) {
this.context = context;
this.list = list;
}
//Pagination
public void updateList(ArrayList<FlowerListPojo> list) {
this.list.addAll(list);
this.notifyDataSetChanged();
}
@Override
public FlowerListAdapter.MyViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View itemView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.flower_list_row, viewGroup, false);
return new FlowerListAdapter.MyViewHolder(itemView);
}
@Override
public void onBindViewHolder(FlowerListAdapter.MyViewHolder holder, int position) {
LinearLayoutManager mLayoutManager;
holder.name.setText(list.get(position).getInfo().getName());
ArrayList<CalenderPojo> listCal = new ArrayList<>();
Glide.with(context).load(list.get(position).getInfo().getImage())
.thumbnail(0.5f)
.crossFade()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(holder.imageFlower);
mLayoutManager = new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false);
holder.recyclerView.setLayoutManager(mLayoutManager);
holder.recyclerView.setItemAnimator(new DefaultItemAnimator());
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
//todays date
Date cToday = Calendar.getInstance().getTime();
String todaysDate = df.format(cToday);
//last day last next 90 days
Calendar c = Calendar.getInstance();
c.add(Calendar.DATE, 90);
Date d = c.getTime();
String lastDate = df.format(d);
List<Date> dates = getDates(todaysDate, lastDate);
for (Date date : dates) {
String dayOfTheWeek = (String) DateFormat.format("EEE", date); // Thursday
String day = (String) DateFormat.format("dd", date); // 20
String monthString = (String) DateFormat.format("MMMM", date); // Jun
String monthNumber = (String) DateFormat.format("MM", date); // 06
String year = (String) DateFormat.format("yyyy", date); // 2013
listCal.add(new CalenderPojo(dayOfTheWeek, day, "200", monthString + " " + year));
}
holder.recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
int firstVisiblePosition = mLayoutManager.findFirstVisibleItemPosition();
if(firstVisiblePosition>=0)
holder.monthName.setText(listCal.get(firstVisiblePosition+3).getMonth());
}
});
holder.recyclerView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
}
});
//Date send to Adapter / Constructor call
holder.adapter = new CalenderAdapter(context, listCal);
holder.recyclerView.setAdapter(holder.adapter);
}
@Override
public int getItemCount() {
if (list.size() != 0)
return list.size();
else return 0;
}
class MyViewHolder extends RecyclerView.ViewHolder {
TextView name;
ImageView imageFlower;
RecyclerView recyclerView;
TextView monthName;
CalenderAdapter adapter;
public MyViewHolder(View itemView) {
super(itemView);
name = itemView.findViewById(R.id.flowerNameFLR);
imageFlower = itemView.findViewById(R.id.flowerImgFLR);
recyclerView = itemView.findViewById(R.id.recycler_view_calender);
monthName = itemView.findViewById(R.id.monthName);
}
}
private static List<Date> getDates(String dateString1, String dateString2) {
ArrayList<Date> dates = new ArrayList<Date>();
java.text.DateFormat df1 = new SimpleDateFormat("yyyy-MM-dd");
Date date1 = null;
Date date2 = null;
try {
date1 = df1.parse(dateString1);
date2 = df1.parse(dateString2);
} catch (ParseException e) {
e.printStackTrace();
}
Calendar cal1 = Calendar.getInstance();
cal1.setTime(date1);
Calendar cal2 = Calendar.getInstance();
cal2.setTime(date2);
while (!cal1.after(cal2)) {
dates.add(cal1.getTime());
cal1.add(Calendar.DATE, 1);
}
return dates;
}
}
Ниже находится класс дочернего адаптера
CalenderAdapter.java
public class CalenderAdapter extends RecyclerView.Adapter<CalenderAdapter.MyViewHolder> {
ArrayList<CalenderPojo> list;
Context context;
private int mSelectedItem = -1;
public CalenderAdapter(Context context, ArrayList<CalenderPojo> listCal) {
this.context = context;
this.list = listCal;
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.date_row, parent, false);
return new MyViewHolder(itemView);
}
@Override
public void onBindViewHolder(MyViewHolder holder, final int position) {
final CalenderPojo listPotn = list.get(position);
holder.day.setText(listPotn.getDay());
holder.date.setText(listPotn.getDate());
holder.price.setText("$ "+listPotn.getPrice());
holder.linearLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mSelectedItem = position;
notifyDataSetChanged();
// ((FlowerListAdapter)context).sendTimedetails(position);
}
});
if (mSelectedItem==position) {
holder.itemView.setBackgroundResource(R.drawable.selected_date_back);
holder.day.setTextColor(context.getResources().getColor(R.color.white));
holder.date.setTextColor(context.getResources().getColor(R.color.white));
holder.price.setTextColor(context.getResources().getColor(R.color.white));
} else {
holder.linearLayout.setBackgroundColor(context.getResources().getColor(R.color.primaryLight2));
holder.day.setTextColor(context.getResources().getColor(R.color.black));
holder.date.setTextColor(context.getResources().getColor(R.color.black));
holder.price.setTextColor(context.getResources().getColor(R.color.black));
}
}
@Override
public int getItemCount() {
if (list.size() != 0 && list !=null)
return list.size();
else return 0;
}
class MyViewHolder extends RecyclerView.ViewHolder {
TextView day, date, price;
LinearLayout linearLayout;
public MyViewHolder(View itemView) {
super(itemView);
day = itemView.findViewById(R.id.day);
date = itemView.findViewById(R.id.date);
price = itemView.findViewById(R.id.price);
linearLayout = itemView.findViewById(R.id.lLayout);
}
}
}
3 ответа
Попробуй это
Создай
interface
как это
public interface ClickPosition {
public void getPosition(int position);
}
Сделайте ниже изменения в вашем
FlowerListAdapter.java :
public class FlowerListAdapter extends RecyclerView.Adapter<FlowerListAdapter.MyViewHolder> {
ArrayList<FlowerListPojo> list;
Context context;
ClickPosition clickPosition;
public FlowerListAdapter(Context context, ArrayList<FlowerListPojo> list) {
this.context = context;
this.list = list;
}
//Pagination
public void updateList(ArrayList<FlowerListPojo> list) {
this.list.addAll(list);
this.notifyDataSetChanged();
}
@Override
public FlowerListAdapter.MyViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View itemView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.flower_list_row, viewGroup, false);
return new FlowerListAdapter.MyViewHolder(itemView);
}
@Override
public void onBindViewHolder(FlowerListAdapter.MyViewHolder holder, int position) {
LinearLayoutManager mLayoutManager;
holder.name.setText(list.get(position).getInfo().getName());
ArrayList<CalenderPojo> listCal = new ArrayList<>();
Glide.with(context).load(list.get(position).getInfo().getImage())
.thumbnail(0.5f)
.crossFade()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(holder.imageFlower);
mLayoutManager = new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false);
holder.recyclerView.setLayoutManager(mLayoutManager);
holder.recyclerView.setItemAnimator(new DefaultItemAnimator());
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
//todays date
Date cToday = Calendar.getInstance().getTime();
String todaysDate = df.format(cToday);
//last day last next 90 days
Calendar c = Calendar.getInstance();
c.add(Calendar.DATE, 90);
Date d = c.getTime();
String lastDate = df.format(d);
List<Date> dates = getDates(todaysDate, lastDate);
for (Date date : dates) {
String dayOfTheWeek = (String) DateFormat.format("EEE", date); // Thursday
String day = (String) DateFormat.format("dd", date); // 20
String monthString = (String) DateFormat.format("MMMM", date); // Jun
String monthNumber = (String) DateFormat.format("MM", date); // 06
String year = (String) DateFormat.format("yyyy", date); // 2013
listCal.add(new CalenderPojo(dayOfTheWeek, day, "200", monthString + " " + year));
}
holder.recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
int firstVisiblePosition = mLayoutManager.findFirstVisibleItemPosition();
if(firstVisiblePosition>=0)
holder.monthName.setText(listCal.get(firstVisiblePosition+3).getMonth());
}
});
holder.recyclerView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
}
});
//Date send to Adapter / Constructor call
holder.adapter = new CalenderAdapter(context, listCal,clickPosition);
holder.recyclerView.setAdapter(holder.adapter);
}
@Override
public int getItemCount() {
if (list.size() != 0)
return list.size();
else return 0;
}
class MyViewHolder extends RecyclerView.ViewHolder {
TextView name;
ImageView imageFlower;
RecyclerView recyclerView;
TextView monthName;
CalenderAdapter adapter;
public MyViewHolder(View itemView) {
super(itemView);
clickPosition= new ClickPosition() {
@Override
public void getPosition(int position) {
Toast.makeText(context, ""+position, Toast.LENGTH_SHORT).show();
}
};
name = itemView.findViewById(R.id.flowerNameFLR);
imageFlower = itemView.findViewById(R.id.flowerImgFLR);
recyclerView = itemView.findViewById(R.id.recycler_view_calender);
monthName = itemView.findViewById(R.id.monthName);
}
}
private static List<Date> getDates(String dateString1, String dateString2) {
ArrayList<Date> dates = new ArrayList<Date>();
java.text.DateFormat df1 = new SimpleDateFormat("yyyy-MM-dd");
Date date1 = null;
Date date2 = null;
try {
date1 = df1.parse(dateString1);
date2 = df1.parse(dateString2);
} catch (ParseException e) {
e.printStackTrace();
}
Calendar cal1 = Calendar.getInstance();
cal1.setTime(date1);
Calendar cal2 = Calendar.getInstance();
cal2.setTime(date2);
while (!cal1.after(cal2)) {
dates.add(cal1.getTime());
cal1.add(Calendar.DATE, 1);
}
return dates;
}
}
Внесите следующие изменения в свой CalenderAdapter.java:
public class CalenderAdapter extends RecyclerView.Adapter<CalenderAdapter.MyViewHolder> {
ArrayList<CalenderPojo> list;
Context context;
private int mSelectedItem = -1;
ClickPosition clickPosition;
public CalenderAdapter(Context context, ArrayList<CalenderPojo> listCal, ClickPosition clickPosition) {
this.context = context;
this.list = listCal;
this.clickPosition = clickPosition;
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.date_row, parent, false);
return new MyViewHolder(itemView);
}
@Override
public void onBindViewHolder(MyViewHolder holder, final int position) {
final CalenderPojo listPotn = list.get(position);
holder.day.setText(listPotn.getDay());
holder.date.setText(listPotn.getDate());
holder.price.setText("$ "+listPotn.getPrice());
holder.linearLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mSelectedItem = position;
notifyDataSetChanged();
clickPosition.getPosition(position);
};
// ((FlowerListAdapter)context).sendTimedetails(position);
}
});
if (mSelectedItem==position) {
holder.itemView.setBackgroundResource(R.drawable.selected_date_back);
holder.day.setTextColor(context.getResources().getColor(R.color.white));
holder.date.setTextColor(context.getResources().getColor(R.color.white));
holder.price.setTextColor(context.getResources().getColor(R.color.white));
} else {
holder.linearLayout.setBackgroundColor(context.getResources().getColor(R.color.primaryLight2));
holder.day.setTextColor(context.getResources().getColor(R.color.black));
holder.date.setTextColor(context.getResources().getColor(R.color.black));
holder.price.setTextColor(context.getResources().getColor(R.color.black));
}
}
@Override
public int getItemCount() {
if (list.size() != 0 && list !=null)
return list.size();
else return 0;
}
class MyViewHolder extends RecyclerView.ViewHolder {
TextView day, date, price;
LinearLayout linearLayout;
public MyViewHolder(View itemView) {
super(itemView);
day = itemView.findViewById(R.id.day);
date = itemView.findViewById(R.id.date);
price = itemView.findViewById(R.id.price);
linearLayout = itemView.findViewById(R.id.lLayout);
}
}
}
Создать интерфейс:
public interface RecyclerClickInterface {
void onClick(View view, int position);
}
Создайте CalenderAdapter следующим образом:
holder.adapter = new CalenderAdapter(context, listCal, new RecyclerClickInterface() {
@Override
public void onClick(View view, int position) {
Log.i(TAG, "position " + position);
}
});
Щелчок элемента адаптера каландра:
holder.item.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mRecyclerClickInterface.onClick(view, position);
}
});
Создать Recycler Touch Listner Class
public class RecyclerTouchListner implements RecyclerView.OnItemTouchListener {
private GestureDetector gestureDetector;
private ClickListener clickListener;
public RecyclerTouchListner(Context context, final RecyclerView recyclerView, final ClickListener clickListener) {
this.clickListener = clickListener;
gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
@Override
public void onLongPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null) {
clickListener.onLongClick(child, recyclerView.getChildAdapterPosition(child));
}
}
});
}
@Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
clickListener.onClick(child, rv.getChildAdapterPosition(child));
}
return false;
}
@Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
@Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
public interface ClickListener {
void onClick(View view, int position);
void onLongClick(View view, int position);
}
}
Тогда в вашем родительском адаптере утилизатора вместо setOnClicklistner используйте следующий код:
childRecyclerView.addOnItemTouchListener(new RecyclerTouchListner(parent.getContext(), childRecyclerView, new RecyclerTouchListner.ClickListener() {
@Override
public void onClick(View view, int position) {
// handle childRecycler click here
}
@Override
public void onLongClick(View view, int position) {
}
}));