我已经提到了一些关于此主题的链接,但我仍然无法理解如何将数据从RecyclerView
传递到Fragment
[在Cardview
点击时打开片段]。以下是我的RecyclerView
课程:
public class PhotoAdapter extends RecyclerView.Adapter<PhotoAdapter.PhotosHolder>
{
static class PhotosHolder extends RecyclerView.ViewHolder
{
CardView cv;
ImageView photo_img;
PhotosHolder(final View itemView)
{
super(itemView);
cv = (CardView) itemView.findViewById(R.id.cv_photo);
photo_img = (ImageView) itemView.findViewById(R.id.thum_photo);
}
}
private List<PhotoInitialise> photo;
private Activity mContext;
public PhotoAdapter(List<PhotoInitialise> photos, Context mContext)
{
this.photo=photos;
this.mContext= (Activity) mContext;
}
@Override
public PhotosHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
View layoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.phototab_layout,parent,false);
return new PhotosHolder(layoutView);
}
@Override
public void onBindViewHolder(PhotosHolder holder, final int position)
{
holder.photo_count.setText(photo.get(position).gettotalImages());
holder.cv.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View view)
{
// want to pass the value to a Fragment here and invoke the Fragment
}
});
}
@Override
public int getItemCount()
{
return photo.size();
}
}
这是应该显示的片段的XML布局:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/photo_detail_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/photodetail_description"
android:textSize="20sp"
android:paddingLeft="5dp"
android:layout_marginTop="5dp"
android:paddingRight="5dp">
</RelativeLayout>
我已经知道如何将值传递给片段,但我永远无法调用布局。现在我应该在我的onClick()
中写什么来启动片段布局?
答案 0 :(得分:0)
实现接口以处理指定片段中的单击。 示例代码结构如下所示。您可以根据需要自定义和使用它:
public InterfaceListItemClickListener{
void listItemClickAction(<parameters to pass>);
}
在你的fragment类中实现这个接口:
public class SampleFragment extends BaseFrgment implements InterfaceListItemClickListener{
@Override
public void listItemClickAction(<parameters to pass>) {
//override the interface function
//handle your click action here
}
//pass the instance of your interface to your adapter like below line
YourAdapter yourAdapter = new YourAdapter(otherParameters, this);
}
在Adapter的构造函数中访问接口:
public YourAdapter(otherParameters, InterfaceListItemClickListener clickListenerInferface ){
//other assignations
this.clickListenerInferface = clickListenerInferface;
}
然后onClick回调你可以调用你的onclick函数:
clickListenerInferface.listItemClickAction(<parameter to pass>);