优化这段代码 private void initPager() { ArrayList<User> list=new ArrayList<>(); ViewPager2 viewPager = findViewById(R.id.view_pager); ArrayList<Fragment> fragments=new ArrayList<>(); User user1=new User(); user1.setSong("等风吹"); user1.setSinger("不是花火呀/小田音乐社"); user1.setImageid(R.drawable.song1); list.add(user1); fragments.add(new ExampleFragment(list)); ViewPagerAdapter pagerAdapter = new ViewPagerAdapter(getSupportFragmentManager(),getLifecycle(),fragments); viewPager.setAdapter(pagerAdapter); }
时间: 2023-05-30 22:03:45 浏览: 188
private void initPager() {
ViewPager2 viewPager = findViewById(R.id.view_pager);
ArrayList<Fragment> fragments = new ArrayList<>();
User user1 = new User();
user1.setSong("等风吹");
user1.setSinger("不是花火呀/小田音乐社");
user1.setImageid(R.drawable.song1);
fragments.add(ExampleFragment.newInstance(user1));
ViewPagerAdapter pagerAdapter = new ViewPagerAdapter(getSupportFragmentManager(), getLifecycle(), fragments);
viewPager.setAdapter(pagerAdapter);
}
// 在 ExampleFragment 中添加 newInstance() 静态方法
public static ExampleFragment newInstance(User user) {
ExampleFragment fragment = new ExampleFragment();
Bundle args = new Bundle();
args.putSerializable("user", user);
fragment.setArguments(args);
return fragment;
}
// 在 ExampleFragment 中获取 User 数据
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mUser = (User) getArguments().getSerializable("user");
}
}
阅读全文