I'm following this implementation tutorial of TabLayout and ViewPager with RecyclerView:
TabLayout and ViewPager with RecyclerView
I'm using the project to test how to get the click action in RecyclerView. To complement, I'm following this post that deals with this subject and the same project in StackOverFlow:
What I did:
My interface
public interface ClickListener {
void itemlistener(int position);
}
RecyclerViewAdapter
public class RecyclerViewAdapter extends RecyclerView.Adapter<TextItemViewHolder> {
String[] items;
ClickListener clicklistener;
public RecyclerViewAdapter(String[] items, ClickListener clicklistener) {
this.items = items;
this.clicklistener = clicklistener;
}
@Override
public TextItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_view_list_item, parent, false);
return new TextItemViewHolder(view);
}
@Override
public void onBindViewHolder(TextItemViewHolder holder, int position) {
holder.bind(items[position]);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public int getItemCount() {
return items.length;
}
}
TextItemViewHolder
public class TextItemViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
private TextView textView;
public TextItemViewHolder(View itemView) {
super(itemView);
textView = (TextView) itemView.findViewById(R.id.list_item);
itemView.setOnClickListener(this);
}
@Override
public void onClick(View view) {
clicklistener.itemlistener(getAdapterPosition());
}
public void bind(String text) {
textView.setText(text);
}
}
FragmentA
public class FragmentA extends Fragment implements ClickListener{
RecyclerView recyclerView;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(
R.layout.fragment, container, false);
return rootView;
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
String[] items = getResources().getStringArray(R.array.tab_A);
RecyclerViewAdapter adapter = new RecyclerViewAdapter(items, this);
recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(adapter);
}
@Override
public void itemlistener(int position) {
Toast.makeText(getContext(), "RecyclerView position is: " + position, Toast.LENGTH_SHORT).show();
}
}
Can not find reference
Why is this implementation error occurring to click on RecyclerView?