[英]How do I pass a Custom Object to a list in a different fragment?
So I have my MainActivity
which has a BottomNavigationView
, in there I have 3 different tabs which redirects me to 3 different fragments when I click them. 所以我有MainActivity
,它具有一个BottomNavigationView
,在其中有3个不同的选项卡,单击它们会将我重定向到3个不同的片段。
In FragmentA
I have a RecyclerView
with items, each item has a button. 在FragmentA
我有一个带有项目的RecyclerView
,每个项目都有一个按钮。 When I click said button I want to send that object over to FragmentB
so I can add it to the ArrayList<CustomObject>
and update the RecyclerView
in FragmentB
to display that item. 当我单击该按钮时,我想将该对象发送到FragmentB
以便可以将其添加到ArrayList<CustomObject>
并更新FragmentB
的RecyclerView
以显示该项目。
The only issue is that I don't know how to send that object over on my button click. 唯一的问题是,我不知道如何在单击按钮时发送该对象。
adapter.setOnItemRemoveListener(new RemoveItemAdapter.OnItemRemoveListener() {
@Override
public void onItemRemove(int position) {
//Do I send it from here?
}
});
First of all implements Parcelable in your Model(Object) class and then from your Fragment A just call this - 首先,在您的Model(Object)类中实现Parcelable ,然后从您的Fragment A中调用它-
Fragment fragmentA = new FragmentGet();
Bundle bundle = new Bundle();
bundle.putParcelable("CustomObject", customObject);
fragmentA .setArguments(bundle);
Also, in Fragment B you need to get the Arguments too - 另外,在片段B中,您也需要获取参数-
Bundle bundle = getActivity().getArguments();
if (bundle != null) {
model = bundle.getParcelable("CustomObject");
}
Your custom object class will look like this - 您的自定义对象类将如下所示-
public class CustomObject implements Parcelable {
private String name;
private String description;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.name);
dest.writeString(this.description);
}
public CustomObject() {
}
protected CustomObject(Parcel in) {
this.name = in.readString();
this.description = in.readString();
}
public static final Parcelable.Creator<CustomObject> CREATOR = new Parcelable.Creator<CustomObject>() {
@Override
public CustomObject createFromParcel(Parcel source) {
return new CustomObject(source);
}
@Override
public CustomObject[] newArray(int size) {
return new CustomObject[size];
}
};
}
Just call the Fragment B from your recycler view item click listener and use the above mentioned code to pass the Custom Object using Parcelable. 只需从您的回收站视图项目单击侦听器中调用Fragment B,然后使用上述代码使用Parcelable传递自定义对象。
Hope it helps. 希望能帮助到你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.