代码之家  ›  专栏  ›  技术社区  ›  Abhishek kumar

RecyclerView在RecyclerView中,获取父适配器中子行的单击位置

  •  1
  • Abhishek kumar  · 技术社区  · 6 年前

    在我的项目要求中,正如在活动中显示的项目列表一样,我将在列表中显示日期和价格,我希望用户选择日期,日期颜色将更改,当点击购物车项目时,应将其添加到卡中。

    问题: 我无法在父RecyclerView中获取子RecyclerView位置 onBindViewHolder .

    是否有任何方法可以在父reycerview中获取子行(日期行)的位置。

    下图显示了三个列表,每个列表中都有日期行列表。当用户点击特定日期时,我希望在OnBindViewholder内的父RecyclerView适配器类上显示该日期。

    enter image description here

    以下是适配器:

    下面是父适配器类

    花式适配器.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;
        }
    }
    

    下面是子适配器类

    日历适配器.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 回复  |  直到 6 年前
        1
  •  1
  •   AskNilesh    6 年前

    试试这个

    创建一个 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;
        }
    
    }
    

    在calendarAdapter.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);
            }
        }
    }
    
        2
  •  1
  •   Shiva Snape    6 年前

    创建Recycler Touch Listner类

    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) {
    
                }
            }));
    
        3
  •  1
  •   Ronak Thakkar    6 年前

    创建接口:

    public interface RecyclerClickInterface {
    void onClick(View view, int position);
    }
    

    创建日历适配器,如下所示:

    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);
       }
    });