Android passing ArrayList to Fragment from Activity

前端 未结 2 1462
抹茶落季
抹茶落季 2020-12-17 01:11

Hi I want to send the data ArrayList to Fragment class ListContentFragment.

In MainActivity I am making a netw

2条回答
  •  無奈伤痛
    2020-12-17 01:44

    If you want to pass an ArrayList to your fragment, then you need to make sure the Model class is implements Parcelable. Here i can show an example.

    public class ObjectName implements Parcelable {
    
    
        public ObjectName(Parcel in) {
            super();
            readFromParcel(in);
        }
    
        public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
            public ObjectName createFromParcel(Parcel in) {
                return new ObjectName(in);
            }
    
            public ObjectName[] newArray(int size) {
    
                return new ObjectName[size];
            }
    
        };
    
        public void readFromParcel(Parcel in) {
            Value1 = in.readInt();
            Value2 = in.readInt();
            Value3 = in.readInt();
    
        }
    
        public int describeContents() {
            return 0;
        }
    
        public void writeToParcel(Parcel dest, int flags) {
            dest.writeInt(Value1);
            dest.writeInt(Value2);
            dest.writeInt(Value3);
        }
    }
    

    then you can add ArrayList to a Bundle object.

    ArrayList arraylist = new Arraylist();  
    Bundle bundle = new Bundle();  
    bundle.putParcelableArrayList("arraylist", arraylist);
    fragment.setArguments(bundle);
    

    After this you can get back this data by using,

    Bundle extras = getIntent().getExtras();  
    ArrayList arraylist  = extras.getParcelableArrayList("arraylist");
    

    At last you can show list with these data in fragment. Hope this will help to get your expected answer.

提交回复
热议问题