When i try to pass bundle variables to my Fragment in android they return as null in the fragment itself, yes I know this question has been asked a lot but this is my first 5 weeks in android and i am completely new to fragments and passing bundles
this is the hero activity code (inside on create)
// create bundle of variables
final Bundle bundle = new Bundle();
bundle.putString("description",description);
bundle.putString("affiliation",affiliation);
bundle.putString("role",role);
bundle.putString("realName",realName);
bundle.putString("occupation",occupation);
bundle.putString("base",base);
bundle.putString("backstory",backstory);
bundle.putInt("difficulty",difficulty);
bundle.putInt("age",age);
// pass data to fragments
FragmentTransaction transaction = getFragmentManager().beginTransaction();
HeroDescriptionFragment descriptionFragment = new HeroDescriptionFragment();
descriptionFragment.setArguments(bundle);
HeroStoryFragment storyFragment = new HeroStoryFragment();
storyFragment.setArguments(bundle);
transaction.commit();
here i am trying to read the bundle in the fragment:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_hero_description, container, false);
// populate hero description
description = this.getArguments().getString("description");
TextView heroDesc = (TextView) rootView.findViewById(R.id.heroDescription);
heroDesc.setText(description);
return rootView;
}
all fragments are created via this pager adapter :
public class PageAdapter extends FragmentStatePagerAdapter {
int numberOfTabs;
public PageAdapter(FragmentManager manager, int numberOfTabs) {
super(manager);
this.numberOfTabs = numberOfTabs;
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new HeroDescriptionFragment();
case 1:
return new HeroStoryFragment();
default:
return null;
}
}
@Override
public int getCount() {
return numberOfTabs;
}
}
I have the feeling i am really close to solving this but i can't figure this out on my own and my teacher has 0 experience in fragments.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…