当我尝试将bundle变量传递给我在Frag中的Fragment时,它们在片段本身中返回null,是的我知道这个问题已经被问了很多,但这是我在android中的前5周,我对片段完全是新的并传递捆绑
这是英雄活动代码(创建内部)
// 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();
这里我试图读取片段中的包:
@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;
}
所有片段都是通过此寻呼机适配器创建的:
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;
}
}
我觉得我真的很接近解决这个问题,但是我无法自己解决这个问题,而且我的老师在片段方面经验不足。
答案 0 :(得分:1)
您的问题是您尝试以两种不同的方式管理片段 - 手动和使用ViewPager。这些是矛盾的 - 选择一个而且只选一个。
您正在事务中设置Bundles参数,然后让Adapter返回没有设置参数的Fragments。要解决您的问题,您必须重构ViewPager方法来设置参数:
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
Fragment frag = HeroDescriptionFragment();
frag.setArguments(createBundle());
return frag;
case 1:
Fragment frag = HeroStoryFragment();
frag.setArguments(createBundle());
return frag;
default:
return null;
}
}
其中createBundle()
用于在原始代码中创建包的方法。
答案 1 :(得分:0)
在你的片段类中使用静态方法,如下所示
public static MyFragment newInstance(String data1,String data2){
MyFragment fragment=new MyFragment();
Bundle budle=new Bundle();
bundle.putString("key",data1);
....
fragment.setArguments(bundle);
return fragment;
}
//then create new Fragment like this
MyFragment f=MyFragment.newInstance("a","b");
return f;