我在片段中解析Json数据。为了获得这个Json数据的视图,我使用了RecycleView。在这个片段中,我展示了一些帖子的简短细节。我希望当用户单击recycleView时,它将转到另一个活动并显示此帖子的详细信息。如何使我的RecycleView可点击?
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_recent_post, container, false);
recentpostRecycleView = (RecyclerView) view.findViewById(R.id.recent_posts);
recentpostRecycleView.setLayoutManager(new LinearLayoutManager(getActivity()));
recentPostAdapter = new RecentPostAdapter(getActivity());
recentpostRecycleView.setAdapter(recentPostAdapter);
sendJsonRequest();
return view;
}
我的RecycleView ScreenShoot:
答案 0 :(得分:2)
你不应该使RecyclerView可点击,而是它的卡片。只需添加android:clickable="true"
到卡布局,然后将ClickListener添加到ChildViews。如果您对此感到困惑,那么slidenerd有一个很好的关于RecyclerViews的教程:https://www.youtube.com/watch?v=zE1E1HOK_E4
答案 1 :(得分:1)
看看这个答案,我认为它最好描述: https://stackoverflow.com/a/24471410/5243853
我目前正在使用类似的解决方案来处理RecycleView项目的点击,但我在适配器的onBindViewHolder方法中设置了监听器。此外,如果需要,您不仅可以将onClickListener设置为整个项目视图,还可以将其设置为其元素。
在您的适配器实现中,您可以:
@Override
public void onBindViewHolder(ViewHolder viewHolder, int position) {
Good good = getItem(position);
Picasso.with(mContext)
.load(good.mainImages)
.placeholder(R.drawable.picasso_placeholder_normal)
.into(viewHolder.mImage, null);
viewHolder.mTitle.setText(good.name);
viewHolder.mCount.setText(good.count);
viewHolder.parent.setOnClickListener(viewHolder); }
适配器的内部类看起来像这样:
class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private View parent;
private ImageView mImage;
private TextView mTitle;
private TextView mCount;
public ViewHolder(View parentView, ImageView image, TextView title, TextView count) {
super(parentView);
parent = parentView;
mImage = image;
mTitle = title;
mCount = count;
}
@Override
public void onClick(View v) {
int position = getAdapterPosition();
Good good = getItem(position);
if (good != null) {
//requestProductCard(good.id, v); //do your stuff here
}
}
}