我已经设置了一个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...");
}
}
}
答案 0 :(得分:0)
是的。您必须通过适配器设置imageview的监听器...类似于下面的代码段...
public class YourAdapter extends RecyclerView.Adapter<YourAdapter.ViewHolder> {
private OnImageClickedListener listener;
public void setListener(OnImageClickedListener listener){
this.listener = listener;
}
public class ViewHolder extends RecyclerView.ViewHolder {
public ImageView imageView;
private ViewHolder(View root) {
super(root);
imageView = root.findViewById(R.id.imageView);
imageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(listener != null) listener.onImageClicked(v.getTag());
}
});
}
}
public interface OnImageClickedListener {
void onImageClicked(Object tag);
}
}
您将按以下方式使用它...
YourAdapter adapter = new YourAdapter();
adapter.setListener(new YourAdapter.OnImageClickedListener{
public void onImageClicked(){
//TODO: display that toast
}
});