由于某种原因,我的片段包含一个字符串数组在我的片段的oncreate方法中出现null。我正在尝试在创建片段时传递一个url数组,以便在我提供不同的图像URL时在imageviews中呈现不同的图像。我最初在构造函数中做了这个,但是android不喜欢我使用的构造函数不是默认构造函数的事实。我假设错误可能来自于在将bundle传递给片段之前调用片段的oncreate方法这一事实,但我不知道如何在不经过构造函数的情况下更快地将信息传递到片段中。
以下是实例化片段的代码。
private void initViewPager() {
viewPager = (ViewPager) findViewById(R.id.view_pager);
List<Fragment> listFragments = new ArrayList<Fragment>();
for(int i = 0; i < tabNames.length; i++)
{
Bundle bundle = new Bundle();
ImageViewerFragment imageViewerFragment = new ImageViewerFragment();
listFragments.add(imageViewerFragment);
switch(tabNames[i])
{
case "All":
bundle.putStringArray("urls", URLS.randomURLs);
break;
case "Zombie":
bundle.putStringArray("urls", URLS.zombieURLS);
break;
case "Captain":
bundle.putStringArray("urls", URLS.captainURLS);
break;
case "Awesome":
bundle.putStringArray("urls", URLS.awesomeURLS);
break;
}
}
MyFragmentPagerAdapter myFragmentPagerAdapter = new MyFragmentPagerAdapter(getSupportFragmentManager(), listFragments);
viewPager.setAdapter(myFragmentPagerAdapter);
viewPager.addOnPageChangeListener(this);
}
My Fragment Class
public class ImageViewerFragment extends Fragment {
GridView mGridView;
ImageAdapter mImageAdapter;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.imageviewerfragment_layout, container, false);
mGridView = (GridView) view.findViewById(R.id.grid_view);
mImageAdapter = new ImageAdapter(getActivity(), getArguments().getStringArray("urls"));
mGridView.setAdapter(mImageAdapter);
return view;
}
}
答案 0 :(得分:3)
您没有将bundle
设置为片段。你没有打电话给imageViewerFragment.setArguments(bundle);