【发布时间】:2023-03-03 09:43:01
【问题描述】:
我的应用程序使用以下结构:
Activity > ViewPager > FragmentStatePagerAdapter > Fragment > RecyclerView
过去我一直在相当舒适地使用 RecyclerViews,但由于某种原因,当我的 RecyclerView 项目放置在 Fragment 中时,我无法让我的 RecyclerView 项目注册点击事件。我的 ViewHolder 如下:
// ViewHolder Class for ExhibitAdapter
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView itemTitleTextView;
public TextView itemDescriptionTextView;
public NetworkImageView itemCoverPhoto;
public ViewHolder(View itemView) {
super(itemView);
itemCoverPhoto = (NetworkImageView) itemView.findViewById(R.id.exhibitThumbnailNIV);
itemTitleTextView = (TextView) itemView.findViewById(R.id.exhibitNameTV);
itemDescriptionTextView = (TextView) itemView.findViewById(R.id.exhibitDescriptionTV);
itemView.setOnClickListener(this);
}
@Override
public void onClick(View view) {
try {
Log.d(TAG, "Exhibit clicked");
Exhibit currentExhibit = exhibits.get(getAdapterPosition());
intent.putExtra(ExhibitContentActivity.EXHIBIT_ID , currentExhibit.getId());
intent.putExtra(ExhibitContentActivity.EXHIBIT_COVER_URL , currentExhibit.getCoverPhotoUrl());
ActivityOptionsCompat options = ActivityOptionsCompat.
makeSceneTransitionAnimation((Activity) adapterContext, itemView.findViewById(R.id.exhibitThumbnailNIV), "profile");
Log.i(TAG, "Attempting to launch detail activity with exhibit id: " + currentExhibit.getId());
adapterContext.startActivity(intent, options.toBundle());
}
catch(IndexOutOfBoundsException e) {
Log.e(TAG, "* Error: Adapter position exceeded the no. of items.");
}
}
}
任何帮助将不胜感激。我尝试按照https://guides.codepath.com/android/Creating-and-Using-Fragments#fragment-listener 中列出的步骤创建片段交互侦听器,但我不确定如何在 RecyclerView 的适配器中实现它。提前致谢!
【问题讨论】:
-
你找到解决办法了吗?
-
@MichaelA。是的,问题只是 1. 我的项目布局绘制时间太长了 2. 我正在处理 ViewHolder 类中的 onClick 逻辑。我通过在片段中创建一个侦听器接口来解决它,在 ViewHolder 的 onClick 中调用该侦听器的 onMyItemClick 方法,然后在我的主活动中实现该侦听器。这让我可以定义当一个项目被点击时要做什么,同时有效地将点击事件冒泡到我的主要活动中。
-
@ShahraizT。您好,您的解决方案是否有示例代码?我有同样的问题,你的解决方案就是我需要的。谢谢。
标签: android android-fragments onclick android-recyclerview fragment