Recyclerview内的Recyclerview,获取父适配器内子行的点击位置

时间:2018-07-11 10:14:02

标签: java android android-recyclerview recycler-adapter

在我的项目需求中,由于活动中显示了项目列表,并且我在列表中显示了日期价格,我希望用户选择日期,日期颜色将更改,并且在点击购物车项目时已添加到卡中。

问题::我无法获得父recyclerView onBindViewHolder中的子recyclerView位置。

有什么方法可以获取父行reyclerview中子行(日期行)的位置。

下面是图像,显示了三个列表,每个列表中都有日期的行列表。当用户点击特定日期时,我希望该日期位于onBindViewHolder中的父recyclerView Adapter类上。

enter image description here

以下是适配器:

以下是父适配器类

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 个答案:

答案 0 :(得分:1)

创建回收站触摸列表器类

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) {

            }
        }));

答案 1 :(得分:1)

创建界面:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
import java.text.MessageFormat;

public class HtmlTablePrinter {

    public static void main(String [] args) {
        new HtmlTablePrinter().displayTable();
    }

    private void displayTable() {
        final JTable table1 = getTable1();
        final JTable table2 = getTable2();
        JButton previewButton = new JButton("Print preview");
        previewButton.addActionListener(actionEvent -> {
            try {
                printPreview(getHtml(table1, table2));
            }
            catch (Exception ex) {
                ex.printStackTrace();
            }
        });
        JPanel panel = new JPanel();
        panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
        panel.add(new JScrollPane(table1));
        panel.add(new JScrollPane(table2));
        JFrame frame = new JFrame("Tables Print Demo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(panel, BorderLayout.CENTER);
        frame.add(previewButton, BorderLayout.SOUTH);
        frame.setLocation(200, 100);
        frame.setSize(500, 500);
        frame.setVisible(true);
    }

    private JTable getTable1() {
        String data [][] = {{"Violet", "Indigo"},
                {"Blue", "Green"},
                {"Yellow", "Orange"},
                {"Red", "Others"}};
        String header [] = {"Colors 1", "Colors 2"};
        return new JTable(data, header);
    }

    private JTable getTable2() {
        TableModel model = new AbstractTableModel() {
            @Override public int getColumnCount() {
                return 2;
            }
            @Override public int getRowCount() {
                return 10;
            }
            @Override public Object getValueAt(int row, int col) {
                return ("Cell at row " + (row+1) + " col " + (col+1));
            }
        };
        return new JTable(model);
    }

    private String getHtml(JTable table1, JTable table2) {
        String style = "<style>table, th, td {border:1px solid #C0C0C0;" +
                "font-family:sans-serif;padding:2px;}</style>";
        StringBuilder line = new StringBuilder();
        line.append("<html>")
            .append("<head>").append(style).append("</head>")
            .append("<body>");
        line = getTableHtml(table1, line);
        line = getTableHtml(table2, line);
        line.append("</body>").append("</html>");
        return line.toString();
    }

    private StringBuilder getTableHtml(JTable table, StringBuilder line) {
        TableModel model = table.getModel();
        line.append("<table>");
        line.append("<tr>");
        for (int j = 0; j < model.getColumnCount(); j++) {
            line.append("<th scope='col'>");
            line.append(model.getColumnName(j));
            line.append("</th>");
        }
        line.append("</tr>");
        for (int i = 0; i < model.getRowCount(); i++) {
            line.append("<tr>");
            for (int j = 0; j < model.getColumnCount(); j++) {
                line.append("<td>");
                line.append(model.getValueAt(i, j));
                line.append("</td>");
            }
            line.append("</tr>");
        }
        line.append("</table>").append("<br/>");
        return line;
    }

    public void printPreview(String html) {
        JDialog dialog = new JDialog();
        dialog.setTitle("Tables Print Preview");
        dialog.setModal(true);
        JEditorPane editorPane = new JEditorPane("text/html", html);
        editorPane.setMargin(new Insets(10, 10, 10, 10));
        editorPane.setEditable(false);
        JButton printButton = new JButton("Print...");
        printButton.addActionListener(actionEvent -> {
            MessageFormat hd = new MessageFormat("Colors & stuff");
            MessageFormat ft = new MessageFormat("Page {0,number,integer}");
            try {
                editorPane.print(hd, ft);
            } catch(Exception ex) { 
                ex.printStackTrace();
            }
        });
        dialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
        JPanel panel = new JPanel();
        panel.add(new JScrollPane(editorPane));
        panel.add(new JSeparator(SwingConstants.VERTICAL));
        panel.add(printButton);
        dialog.add(panel);
        dialog.setSize(500, 700);
        dialog.setLocation(300, 50);
        dialog.setVisible(true);
    }
}

像这样创建CalenderAdapter:

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

答案 2 :(得分:1)

尝试一下

  

像这样创建一个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);
        }
    }
}