我尝试为单击的“回收者”视图上的按钮着色。
public class OneActiveButtonAdapter
extends RecyclerView.Adapter<OneActiveButtonAdapter.ViewHolder> {
public class ViewHolder extends RecyclerView.ViewHolder
implements View.OnClickListener {
private Button button;
private WeakReference<ClickListener> listenerWR;
ViewHolder(View view, ClickListener listener) {
super(view);
button = view.findViewById(R.id.button);
button.setBackgroundColor(Color.WHITE);
listenerWR = new WeakReference<>(listener);
}
@Override
public void onClick(View view) {
Log.d("PRESSED", "BUTTON IS PRESSED");
}
}
public interface ClickListener {
void onPositionClicked(int position);
}
private ClickListener clickListener;
private List<Payable> buttons;
private int indexOfActivatedButton = -1;
public OneActiveButtonAdapter(List<Payable> buttons, ClickListener clickListener) {
this.buttons = buttons;
this.clickListener = clickListener;
}
@Override
public int getItemCount() {
return buttons.size();
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int ind) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.buttons_linear_layout,
parent, false);
return new ViewHolder(view, clickListener);
}
@Override
public void onBindViewHolder(ViewHolder viewHolder, int ind) {
viewHolder.button.setText(buttons.get(ind).getTitle());
if (indexOfActivatedButton == ind) {
viewHolder.button.setBackgroundColor(Color.GREEN);
} else {
viewHolder.button.setBackgroundColor(Color.WHITE);
}
}
}
'''
还有代码,当我为'''RecyclerView'''创建适配器时:
'''
OneActiveButtonAdapter foodRVAdapter = new OneActiveButtonAdapter(food,
new OneActiveButtonAdapter.ClickListener() {
@Override
public void onPositionClicked(int position) {
Log.d("POSITION", String.valueOf(position));
}
});
'''
当我尝试单击RecyclerView上的某些按钮时,我希望看到日志,但不会输出。我也尝试为按钮设置setOnClickListener,但是它并没有改变。 这可能是什么麻烦?
答案 0 :(得分:0)
因为您没有将listener设置为按钮。
删除listenerWR = new WeakReference<>(listener);
并尝试使用此button.setOnClickListener(this);
希望这会有所帮助。