pass value from activity to fragment using bundle in tabbed activity

前端 未结 2 1178
-上瘾入骨i
-上瘾入骨i 2021-01-27 23:47

I am a java-illiterate, and still trying to develop a app for my personal use. I have started with android-studio\'s \"Tabbed-Activity\", and mostly unaltered except a fragment

2条回答
  •  失恋的感觉
    2021-01-28 00:22

    This way you can pass data from your mainActivity to fragment

    MainActivity onCreate method

         adapter = new Adapter(getChildFragmentManager());
    
         SquadsTeamListFragment  teamA =                
            SquadsTeamListFragment.newInstance(teamAData,teamBData
            adapter.addFragment(teamA, teamAName);
            viewPager.setAdapter(adapter);
            tabLayout.setupWithViewPager(viewPager);
    

    use this adapter in your main activity

     static class Adapter extends FragmentStatePagerAdapter {
        private final List mFragmentList = new ArrayList<>();
        private final List mFragmentTitleList = new ArrayList<>();
    
        Adapter(FragmentManager manager) {
            super(manager);
        }
        @Override
        public Fragment getItem(int position) {
            return mFragmentList.get(position);
        }
        @Override
        public int getCount() {
            return mFragmentList.size();
        }
        void addFragment(Fragment fragment, String title) {
            mFragmentList.add(fragment);
            mFragmentTitleList.add(title);
        }
        @Override
        public CharSequence getPageTitle(int position){
            return mFragmentTitleList.get(position);
         }
      }
    

    receive data to fragment (SquadsTeamListFragment .java)

       public static SquadsTeamListFragment newInstance(String playerList, String   
      oppPlayerList) {
        SquadsTeamListFragment fragment = new SquadsTeamListFragment();
        Bundle args = new Bundle();
        args.putString(ARG_TEAM_DATA, playerList);
        args.putString(ARG_OPP_TEAM_DATA, oppPlayerList);
    
        fragment.setArguments(args);
        return fragment;
    }
       @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            playerList = getArguments().getString(ARG_TEAM_DATA);
            oppPlayerList = getArguments().getString(ARG_OPP_TEAM_DATA);
    
        }
    }
    

提交回复
热议问题