如何在两个按钮上处理相同的代码单击事件

How to handle same code on two button Click Event

我正在使用 Recyclerview 来显示一些问题和答案。点击箭头按钮做一些事情,然后点击 tvTitle 做同样的事情。

有什么方法可以避免在两次点击侦听器上重复相同的代码。我不能在 onBindViewHolder 之外使用该方法,因为我正在使用无法在 onBindViewHolder 之外处理的 viewholder 项。

请帮忙。

public void onBindViewHolder(@NonNull Adapter.ViewHolder viewHolder, int position) {

Model model = filteredList.get(position);

viewHolder.tvTitle.setText(model.getQuestion());
viewHolder.tvDescription.setText(model.getAnswer());

viewHolder.btnArrow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //Do some stuff
                if (viewHolder.tvDescription.getVisibility() == View.GONE) {
                    viewHolder.tvDescription.setVisibility(View.VISIBLE);
                    viewHolder.btnArrow.setBackgroundResource(R.drawable.ic_arrow_up1);
                } else {
                    viewHolder.tvDescription.setVisibility(View.GONE);
                    viewHolder.btnArrow.setBackgroundResource(R.drawable.ic_arrow_down1);
                }
            }
        });

viewHolder.tvTitle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //Do some stuff
                if (viewHolder.tvDescription.getVisibility() == View.GONE) {
                    viewHolder.tvDescription.setVisibility(View.VISIBLE);
                    viewHolder.btnArrow.setBackgroundResource(R.drawable.ic_arrow_up1);
                } else {
                    viewHolder.tvDescription.setVisibility(View.GONE);
                    viewHolder.btnArrow.setBackgroundResource(R.drawable.ic_arrow_down1);
                }
            }
        });
    }

我通过使用一种方法并在其中传递 viewholder 获得了我想要的答案:

viewHolder.btnArrow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                doAction(viewHolder);
            }
        });

        viewHolder.tvTitle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                doAction(viewHolder);
            }
        });

方法:

private void doAction(final ViewHolder viewHolder) {

        if (viewHolder.tvDescription.getVisibility() == View.GONE) {
            viewHolder.tvDescription.setVisibility(View.VISIBLE);

            viewHolder.btnArrow.setBackgroundResource(R.drawable.ic_arrow_up1);
        } else {
            viewHolder.tvDescription.setVisibility(View.GONE);
            viewHolder.btnArrow.setBackgroundResource(R.drawable.ic_arrow_down1);
        }
    }