我有一个对象,我们将其称为Shop
,并且该对象具有一组称为Offers
的对象。
我应该如何将Bundle
与我的对象一起使用,以将其从第一个片段发送到用onClickListener
打开的片段?
蜜蜂Shop
,我需要解析的对象类似:
public class Shop {
private String name;
private String schedule;
private String direction;
private List<Offer> Offers = new ArrayList<Offer>();
}
和Offer
之类的东西:
public class Offer {
private int packsAvailable;
private String description;
}
该函数调用第二个片段:
public void onClick(View v) {
Fragment shopping = new OffersDisplayFragment();
//Instantiate fragment
FragmentTransaction fragmentTransaction =
activity.getSupportFragmentManager()
.beginTransaction();
fragmentTransaction.replace(R.id.fragment, shopping);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
答案 0 :(得分:0)
您可以通过添加一种方法来创建下一个片段的实例来实现它(我假设它是OffersDisplayFragment)。
在您的片段中添加以下方法,以便我们可以创建带有捆绑软件的片段:
public class OffersDisplayFragment extends Fragment {
public static final String SHOP_EXTRA = "shopExtra";
// Creates a new fragment given a Shop
public static OffersDisplayFragment newInstance(Shop shop) {
OffersDisplayFragment fragment = new OffersDisplayFragment();
Bundle args = new Bundle();
args.putSerializable(SHOP_EXTRA, shop);
fragment.setArguments(args);
return fragment;
}
}
然后更新或创建片段的onCreate方法以处理捆绑包:
public class OffersDisplayFragment extends Fragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get back arguments
Shop = (Shop) getArguments().getSerializable(SHOP_EXTRA);
// Do something with the Shop here
}
}
在这一点上,Android Studio将抱怨您的Shop
模型无法序列化。这是预期的,因为我们尚未将Shop声明为serializable
。因此,将您的Shop and Offer更改为可序列化,如下所示:
public class Shop implements Serializable {
...
}
和
public class Offer implements Serializable {
...
}
现在,您可以像这样在您的点击侦听器中创建带有捆绑包的片段:
public void onClick(View v) {
Fragment shoppingFragment = OffersDisplayFragment.newInstance(shop);
...
// show the fragment with the fragment transaction.
}
有了可行的解决方案后,请尝试使用Parcelable
代替Serializable
。