【发布时间】:2018-10-11 10:21:50
【问题描述】:
我正在制作一个连接到 WordPress 的 Android 电子商务应用程序。在我的应用中,我有两个片段:商店片段(其中包含从网站获取的产品)和我的愿望清单片段(包含愿望清单产品在里面)。我还有两个列表:一个用于检索到的产品,另一个用于愿望清单产品。愿望清单产品列表包含检索到的产品列表中的每个产品的索引,因此我可以稍后获取完整的详细信息(图片、描述等)。
我面临的问题是在将产品添加到愿望清单时,我希望能够单击 商店片段 中的愿望清单按钮,并且愿望清单产品将显示在 我的愿望清单中片段。我在网上搜索了很多,我发现我应该使用notifyDataSetChanged,但我没有找到任何关于如何从其他 Fragment 调用它的示例。
如果我理解正确,我应该从ShopProductAdapter 调用WishlistProductAdapter,但我是Android 开发的初学者,所以我不确定我是否可以自己完成。
我相信 MyWishlist.java(片段)中的这段代码可以提供帮助:
//getting the recyclerview from xml
RecyclerView recyclerView = (RecyclerView) getView().findViewById(R.id.wishlist_products);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new StaggeredGridLayoutManager(getResources().getInteger(R.integer.products_column_count), StaggeredGridLayoutManager.VERTICAL));
JSONArray shop_products = //fetched from website, done in MainActivity;
ArrayList<String> wishlist_products = ["3","0"]; // It contains product of index 0 and product of index 3 inside shop_products
//initializing the productlist
List<Product> productList = new ArrayList<>();
for (int i=0; i<wishlist_products.size(); i++) {
String index = wishlist_products.get(i);
JSONObject JO = (JSONObject) shop_products.get(Integer.parseInt(index));
productList.add(
new Product(
i, //index
Integer.parseInt(JO.get("id").toString()), //id
JO.get("title").toString(), //title
null,
null,
JO.get("price").toString(), //price
JO.get("featured_image_url").toString(), //image_url
null
)
);
}
//creating recyclerview adapter
adapter = new WishlistProductAdapter(getActivity().getApplicationContext(), productList);
//setting adapter to recyclerview
recyclerView.setAdapter(adapter);
编辑:
和Shop.java除了for循环(片段)是一样的:
for (int i=0; i<shop_products.length(); i++) {
JSONObject JO = (JSONObject) shop_products.get(i);
productList.add(
new Product(
i,
Integer.parseInt(JO.get("id").toString()),
JO.get("title").toString(),
null,
null,
JO.get("price").toString(),
JO.get("featured_image_url").toString(),
null
)
);
}
编辑:
我的代码片段、适配器和 MainActivity 在这里:https://ufile.io/25z9e
非常感谢任何帮助!
【问题讨论】:
-
您应该为 ShopFragment 和 WishlistFragment 提供代码。这些怎么关联? ShopFragment 中是否有对 WishlistFragment 的引用?
-
添加了商店片段代码。不,两者之间没有关系,wishlist_products 存储在 SharedPreferences 中。两个片段都像这样初始化:
SectionsStatePagerAdapter adapter = new SectionsStatePagerAdapter(getSupportFragmentManager()); adapter.addFragment(new Shop(), "Shop"); adapter.addFragment(new MyWishlist(), "My Wishlist"); viewPager.setAdapter(adapter);
标签: android android-fragments arraylist android-recyclerview