[英]How do I pass a Custom Object to a list in a different fragment?
所以我有MainActivity
,它具有一個BottomNavigationView
,在其中有3個不同的選項卡,單擊它們會將我重定向到3個不同的片段。
在FragmentA
我有一個帶有項目的RecyclerView
,每個項目都有一個按鈕。 當我單擊該按鈕時,我想將該對象發送到FragmentB
以便可以將其添加到ArrayList<CustomObject>
並更新FragmentB
的RecyclerView
以顯示該項目。
唯一的問題是,我不知道如何在單擊按鈕時發送該對象。
adapter.setOnItemRemoveListener(new RemoveItemAdapter.OnItemRemoveListener() {
@Override
public void onItemRemove(int position) {
//Do I send it from here?
}
});
首先,在您的Model(Object)類中實現Parcelable ,然后從您的Fragment A中調用它-
Fragment fragmentA = new FragmentGet();
Bundle bundle = new Bundle();
bundle.putParcelable("CustomObject", customObject);
fragmentA .setArguments(bundle);
另外,在片段B中,您也需要獲取參數-
Bundle bundle = getActivity().getArguments();
if (bundle != null) {
model = bundle.getParcelable("CustomObject");
}
您的自定義對象類將如下所示-
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];
}
};
}
只需從您的回收站視圖項目單擊偵聽器中調用Fragment B,然后使用上述代碼使用Parcelable傳遞自定義對象。
希望能幫助到你。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.