如何在RecyclerView上设置onClickListener

时间:2017-04-26 20:02:36

标签: java android android-recyclerview onclicklistener

我有一个简单的问题,我无法在recyclerview上设置onClickListener,我不想在recyclerview的项目上设置onClickListener,只是在recyclerview本身,我尝试了普通的方式而且它没有工作

(我试图在父布局上设置onClickListener,但由于我在recyclerview上设置的LinearLayoutManager,它不起作用的奇怪事情:|)

这是我的代码:

mRecyclerView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.d("onClick","Clicked");
        }
    });

适配器:

public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
private List<Message> mMessage;

public static class ViewHolder extends RecyclerView.ViewHolder{
    private TextView txtSender;
    private TextView txtMessage;

    public ViewHolder(View v) {
        super(v);
        txtSender = (TextView) v.findViewById(R.id.txtSender);
        txtMessage = (TextView) v.findViewById(R.id.txtText);
    }

}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View inflatedView = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.recyclerview_item_row, parent, false);
    return new ViewHolder(inflatedView);
}


public RecyclerAdapter(List<Message> messages) {
    mMessage = messages;
}

@Override
public void onBindViewHolder(ViewHolder holder, int position) {
    Message msg = mMessage.get(position);
    holder.txtSender.setText(msg.getSender());
    holder.txtMessage.setText(msg.getmessage());
}

@Override
public int getItemCount() {
    return mMessage.size();
}

1 个答案:

答案 0 :(得分:2)

根据您的需要,您需要修改R.layout.recyclerview_item_row。使用安装了LinearLayoutTextViewR.id.txtSender)的安卓R.id.txtText

修改您的ViewHolder,如下所示:

public static class ViewHolder extends RecyclerView.ViewHolder
{
private LinearLayout lvContainer;
private TextView txtSender;
private TextView txtMessage;

public ViewHolder(View v) {
    super(v);
    lvContainer = (LinearLayout) v.findViewById(R.id.lv_container); // R.id.lv_container this should be in your R.layout.recyclerview_item_row
    txtSender = (TextView) v.findViewById(R.id.txtSender);
    txtMessage = (TextView) v.findViewById(R.id.txtText);
}
}

修改您的onBindViewHolder,如下所示

@Override
public void onBindViewHolder(ViewHolder holder, int position) {
Message msg = mMessage.get(position);
holder.txtSender.setText(msg.getSender());
holder.txtMessage.setText(msg.getmessage());
holder.lvContainer.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        //Handle your click here
    }
});
}