I've set up a recyclerView which contains 4 images inside a fragment. I want a toast to appear after clicking the image. I've set up the recyclerAdapter successfully and implemented a listener in the main activity. Should I be trying to set up a clickable image from the recyclerAdapter and not recyclerView? Thanks for any help!
public class topFragment extends Fragment {
RecyclerView recyclerView;
private int[] images = {R.drawable.1, R.drawable.2, R.drawable.3, R.drawable.4};
private RecyclerView.LayoutManager layoutManager;
private RecyclerAdapter recyclerAdapter;
private OnImageListener onImageListener;
public interface OnImageListener{
public void onImageListener(int[] i);
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.top_fragment_layout, container, false);
recyclerView=view.findViewById(R.id.recyclerView);
layoutManager = new GridLayoutManager(getContext(), 4);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(layoutManager);
recyclerAdapter = new RecyclerAdapter(images);
recyclerView.setAdapter(recyclerAdapter);
recyclerView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//RecyclerView.ViewHolder viewHolder= new RecyclerAdapter.ImageViewHolder(view.findViewById(R.id.album));
for(int i=0; i<images.length; i++){
RecyclerAdapter rA = new RecyclerAdapter(images);
if (rA.equals(0)){
Toast.makeText(getContext(), "1!", Toast.LENGTH_SHORT).show();
}
if (rA.equals(1)){
Toast.makeText(getContext(), "2!", Toast.LENGTH_SHORT).show();
}
if (rA.equals(2)){
Toast.makeText(getContext(), "3!", Toast.LENGTH_SHORT).show();
}
if (rA.equals(3)){
Toast.makeText(getContext(), "4!", Toast.LENGTH_SHORT).show();
}
onImageListener.onImageListener(images);
}
}
});
return view;
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
Activity activity = (Activity)context;
try{
onImageListener = (OnImageListener)activity;
}
catch (ClassCastException e){
throw new ClassCastException(activity.toString()+"must implement onImage...");
}
}
}