我有一个回收站视图,该视图已在此处实现扩展。我想在回收器视图的子视图上实现 onClickListener,这样当我单击子视图时,我会收到一条 Toast 消息,显示子文本视图中包含的文本。
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
final Item item = data.get(position);
switch (item.type) {
case HEADER:
final MyViewHolder itemController = (MyViewHolder) holder;
itemController.referalItem = item;
itemController.alphabet.setText(item.text.toString());
if (item.invisibleChildren == null) { itemController.btn_expand_toggle.setImageResource(R.mipmap.knob_add);
} else { itemController.btn_expand_toggle.setImageResource(R.mipmap.knob_remove);
}
itemController.btn_expand_toggle.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (item.invisibleChildren == null) {
item.invisibleChildren = new ArrayList<Item>();
int count = 0;
int pos = data.indexOf(itemController.referalItem);
while (data.size() > (pos + 1) && data.get(pos + 1).type == CHILD) {
item.invisibleChildren.add(data.remove(pos + 1));
count++;
}
notifyItemRangeRemoved(pos + 1, count);
itemController.btn_expand_toggle.setImageResource(R.mipmap.knob_add);
} else {
int pos = data.indexOf(itemController.referalItem);
int index = pos + 1;
for (Item i : item.invisibleChildren) {
data.add(index, i);
index++;
}
notifyItemRangeInserted(pos + 1, index - pos - 1);
itemController.btn_expand_toggle.setImageResource(R.mipmap.knob_remove);
item.invisibleChildren = null;
}
}
});
break;
case CHILD:
final TextView itemTextView = (TextView) holder.itemView;
try {
itemTextView.setText(data.get(position).text.toString());
itemTextView.setOnClickListener(new View.OnClickListener() { //setting the onclicklistener
@Override
public void onClick(View v) throws NullPointerException {
Toast.makeText(context, itemTextView.getText().toString(), Toast.LENGTH_SHORT).show(); //Gives nullpointer error
}
});
} catch (NullPointerException e){
}
break;
但是,每当我单击 recyclerview 中的孩子时,我都会得到 NullPointerException。任何帮助将不胜感激。谢谢你。