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.
In FragmentA
I have a RecyclerView
with items, each item has a button. 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.
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 -
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 -
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.
Hope it helps.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.