onclick事件中打开片段适配器遇到困难怎么解决
来源:爱站网时间:2022-07-19编辑:网友分享
本文主要分享下onclick事件中打开片段适配器遇到困难怎么解决的内容,感兴趣的朋友一定不要错过这篇问题,接下来就让爱站技术频道小编带大家了解了解内容吧!
问题描述
我正在尝试运行从在线教程中获得的一些代码,该教程编写了一个包含recyclerview的片段,但是在onclick事件中打开活动时遇到了一些困难。我的适配器在下面
public class ItemAdapter extends RecyclerView.Adapter {
private final ArrayList mArrayList;
private Context mcontext;
ItemAdapter(ArrayList mArrayList) {
this.mArrayList = mArrayList;
}
@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
mcontext = parent.getContext();
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.listing_item, parent, false);
return new MyViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
//Glide.with(mcontext).load(mArrayList.get(position).getImage()).into(holder.item_image);
holder.item_name.setText(mArrayList.get(position).getTitle());
holder.item_description.setText(mArrayList.get(position).getDescription());
holder.item_tags.setText(mArrayList.get(position).getTags());
Log.d("MyAdapter", "position: " + position);
}
@Override
public int getItemCount() {
return mArrayList.size();
}
class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private final ImageView item_image;
private final TextView item_name;
private final TextView item_description;
private final TextView item_tags;
private final LinearLayout cardViewLayout;
MyViewHolder(View view) {
super(view);
item_image = view.findViewById(R.id.item_image);
item_name = view.findViewById(R.id.item_name);
item_description = view.findViewById(R.id.item_description);
item_tags = view.findViewById(R.id.item_tags);
cardViewLayout = view.findViewById(R.id.cardViewLayout);
cardViewLayout.setOnClickListener(this);
}
@Override
public void onClick(View view) {
Intent intent = new Intent(mcontext, ItemView.class);
mcontext.startActivity(intent);
}
}
}
当我运行代码时,当我单击一个项目时没有任何反应,并且在logcat中也没有看到任何错误
解决方法:
我的想法是,在您的适配器应用程序中的某些活动中,您只需在适配器的setOnItemClickListener
上调用该活动
private void loadItemsData() {
RecyclerView itemsRecyclerView = view.findViewById(R.id.posts_recycler_view);
itemsRecyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
itemsRecyclerView.setLayoutManager(layoutManager);
ItemAdapter myadapter = new ItemAdapter(new ArrayList(), getContext());
myadapter.setOnItemClickListener(new ItemAdapter.OnItemClickListener() {
@Override
public void onItemClick(View view, PostItems items) {
ViewItem.passingIntent(getActivity(), items.postid);
}
});
itemsRecyclerView.setAdapter(ListAdapter );
}
然后一旦完成,您就进入了接收器活动,并让获取传递给它的变量让路
public static void passingIntent(Activity activity, Integer postid){
Intent intent = new Intent(activity, ViewItem.class);
intent.putExtra(MY_ITEM, postid);
activity.startActivity(intent);
}
最近我在其中一个应用中使用了这种方法
onclick事件中打开片段适配器遇到困难怎么解决的问题内容朋友们都了解清楚了吧!想要收集不同类型的技术文章咨询,来我们爱站技术频道网站翻阅相关文章阅读即可。