android - Pass data from Activity to Fragment in ViewPager

后端 未结 6 536
夕颜
夕颜 2020-12-29 07:41

I have a simple Activity with TabLayout, ViewPager and 2 Fragments in it. Here\'s my Activity:

public class ManagementCompanyOverviewActivity extends BaseAct         


        
6条回答
  •  囚心锁ツ
    2020-12-29 08:10

    You could also in your adapter's constructor take in the data you want to display in the fragment and set the arguments before returning a new fragment

    public class ViewPagerAdapter extends FragmentStatePagerAdapter {
    private Weather weather;
    
    ViewPagerAdapter(FragmentManager fm, Weather weather) {
        super(fm);
        this.weather = weather;
    }
    
    @Override
    public Fragment getItem(int position) {
        switch (position) {
            case 0:
                Bundle bundle = new Bundle();
                WeatherFragment weatherFragment = new WeatherFragment();
                bundle.putParcelable("weather", weather);
                weatherFragment.setArguments(bundle);
                return weatherFragment;
            case 1:
                return new PoemFragment();
            default:
                return new EmptyFragment();
        }
    }
    

提交回复
热议问题