How do I pass a Custom Object to a list in a different fragment?

前端 未结 1 1491
温柔的废话
温柔的废话 2021-01-28 10:58

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 t

1条回答
  •  情歌与酒
    2021-01-28 11:31

    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 CREATOR = new Parcelable.Creator() {
            @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.

    0 讨论(0)
提交回复
热议问题