在適配器類,內onBindViewHolder()方法,就可以收聽到整個行作爲註冊以下:
vh1.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Toast.makeText(ComplexRecyclerViewAdapter.this, "Item no: "+ position, Toast.LENGTH_LONG).show;
Toast.makeText(v.getContext(), "General click !", Toast.LENGTH_SHORT).show();
}
});
如果要註冊監聽到行佈局,可以內部的特定視圖做到這一點,如下所示:
vh1.getButton().setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Toast.makeText(ComplexRecyclerViewAdapter.this, "Item no: "+ position, Toast.LENGTH_LONG).show;
Toast.makeText(v.getContext(), "Button is clicked ! ", Toast.LENGTH_SHORT).show();
}
});
的適配器類的全部代碼:
@Override
public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) {
switch (viewHolder.getItemViewType()) {
case USER:
ViewHolder1 vh1 = (ViewHolder1) viewHolder;
configureViewHolder1(vh1, position);
break;
}
}
private void configureViewHolder1(ViewHolder1 vh1, int position) {
User user = (User) items.get(position);
if (user != null) {
vh1.getLabel1().setText("Name: " + user.name);
vh1.getLabel2().setText("Hometown: " + user.hometown);
vh1.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Toast.makeText(ComplexRecyclerViewAdapter.this, "Item no: "+ position, Toast.LENGTH_LONG).show;
Toast.makeText(v.getContext(), "General click !", Toast.LENGTH_SHORT).show();
}
});
vh1.getButton().setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Toast.makeText(ComplexRecyclerViewAdapter.this, "Item no: "+ position, Toast.LENGTH_LONG).show;
Toast.makeText(v.getContext(), "Button is clicked ! ", Toast.LENGTH_SHORT).show();
}
});
}
}
ViewHolder1.java
public class ViewHolder1 extends RecyclerView.ViewHolder {
private TextView label1, label2;
private Button button;
public ViewHolder1(View v) {
super(v);
...
button = (Button) v.findViewById(R.id.button);
}
public Button getButton() {
return button;
}
public void setButton(Button button) {
this.button = button;
}
}
您的數據是否正確顯示?你在哪裏設置了適配器,請分享該代碼? –
作爲begginer更好地嘗試一些教程,http://www.androidhive.info/2016/01/android-working-with-recycler-view/ – darwin