我在回收者视图中有一个产品列表。按下某个项目后,您将进入第二个活动,以显示与该产品有关的更多信息。我正在尝试实现viewPager。遵循CodingWithMitch的教程,但在他的示例中,他拥有随机数据,可以轻松获取它们。
ArrayList<Fragment> fragments = new ArrayList<>();
Hat[] hats = Hats.getHats();
for(Hat hat: hats){
ViewPagerItemFragment fragment = ViewPagerItemFragment.getInstance(hat);
fragments.add(fragment);
}
MyPagerAdapter pagerAdapter = new MyPagerAdapter(getSupportFragmentManager(), fragments);
mMyViewPager.setAdapter(pagerAdapter);
mTabLayout.setupWithViewPager(mMyViewPager, true);
[不幸的是,对我来说,数据是从Livedata对象获取的。如何循环或遍历实时数据以提取所有产品对象,以便设置片段!
ArrayList<Fragment> fragments = new ArrayList<>();
final MarketViewModel marketViewModel = new ViewModelProvider(this).get(MarketViewModel.class);
MutableLiveData<List<Product>> products = marketViewModel.getProductInfo("parentID");
//What to do here !!!
/*for (:) {
ProductInfoFragment fragment = ProductInfoFragment.getInstance(products);
fragments.add(fragment);
}*/
ProductPagerAdapter adapter = new ProductPagerAdapter(getSupportFragmentManager(), 0, fragments);
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager, true);
也显示了整个产品。但是如何先显示按下的项目用户点击的那个。然后用户将可以左右交换整个列表!!
编辑:我尝试过这个!但现在它显示空白页。
ArrayList<Fragment> fragments = new ArrayList<>();
final MarketViewModel marketViewModel = new ViewModelProvider(this).get(MarketViewModel.class);
marketViewModel.getProductInfo("parentID");
marketViewModel.getProductInfo("parentID").observe(this, products -> {
for (int i = 0; i < products.size(); i++) {
Product product = products.get(i);
ProductInfoFragment fragment = ProductInfoFragment.getInstance(product);
fragments.add(fragment);
}
});
ProductPagerAdapter adapter = new ProductPagerAdapter(getSupportFragmentManager(), 0, fragments);
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager, true);
[ViewPager
提交新数据后,请尝试构建LiveData
适配器,因为ViewPager
似乎是用免费数据适配器初始化的,该适配器的代码在返回LiveData
之前运行。
所以您可以尝试:
ArrayList<Fragment> fragments = new ArrayList<>();
final MarketViewModel marketViewModel = new ViewModelProvider(this).get(MarketViewModel.class);
marketViewModel.getProductInfo("parentID");
marketViewModel.getProductInfo("parentID").observe(this, products -> {
for (int i = 0; i < products.size(); i++) {
Product product = products.get(i);
ProductInfoFragment fragment = ProductInfoFragment.getInstance(product);
fragments.add(fragment);
}
ProductPagerAdapter adapter = new ProductPagerAdapter(getSupportFragmentManager(), 0, fragments);
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager, true);
});