【发布时间】:2019-05-01 03:19:49
【问题描述】:
我已经设置了一个 recyclerView,它在一个片段中包含 4 个图像。我希望在单击图像后出现敬酒。我已经成功设置了 recyclerAdapter 并在主要活动中实现了一个监听器。我应该尝试从 recyclerAdapter 而不是 recyclerView 设置可点击的图像吗?感谢您的帮助!
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...");
}
}
}
【问题讨论】:
-
“我应该尝试从 recyclerAdapter 而不是 recyclerView 设置可点击的图像吗?” – 基本上,是的。
RecyclerView不会触发OnClickListener。以this post 为例。
标签: android android-recyclerview fragment clickable