我有一个包含图像和textview的布局的fragmentpageradapter,我希望两者都能改变。
我试图调整以下代码(在网络上找到了不同的地方 - 如果原作者知道我想要承认)
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new DetailFragment();
case 1:
return new ImageFragment(R.drawable.human);
case 2:
return new ImageFragment(R.drawable.logo);
default:
return null;
}
}
}
}
....控制一个班级
public class ImageFragment extends Fragment {
private final int imageResourceId;
public ImageFragment(int imageResourceId) {
this.imageResourceId = imageResourceId;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.e("Test", "hello");
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.image_layout, container, false);
ImageView imageView = (ImageView) view.findViewById(R.id.imageView1);
imageView.setImageResource(imageResourceId);
return view;
}
}
现在代码运行但是抛出错误 "片段应该有一个空的构造函数"所以我试着从这里调整代码 Do fragments really need an empty constructor? 给出以下内容 - 我试图只发送一个页面,其中一个字符串和一个图像以相对布局形式发送到片段。以下代码编译但不会运行。我认为最糟糕的错误在主要源代码中。:
public static class MyAdapter extends FragmentPagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
@Override
public int getCount() {
return 1;
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0: {
ImageFragment f = (ImageFragment) new Fragment();
Bundle bdl = new Bundle(2);
bdl.putInt("theShape", R.string.shape1);
bdl.putInt("theImage", R.drawable.triangle);
f.setArguments(bdl);
return f;
}
.....这里是片段的内脏
public int stringResourceId;
public int imageResourceId;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.e("Test", "bollocks");
stringResourceId = getArguments().getInt("theString");
imageResourceId = getArguments().getInt("theImage");
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.layout_shapes, container, false);
ImageView imageView = (ImageView) view.findViewById(R.id.imageView1);
imageView.setImageResource(imageResourceId);
return view;
}
}
感谢。任何提示赞赏