我正在尝试创建一个显示存储在res
文件夹中的字符串的应用。我试图用viewpager和片段来实现它。安装后,它显示9个页面,所有9个页面中的数组中包含第一个字符串。我应该在哪里进行更改以使其正确?
public class MainActivity extends FragmentActivity {
ViewPager mViewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mViewPager = (ViewPager) findViewById(R.id.pager);
SwipeAdapter swipeAdapter=new SwipeAdapter(getSupportFragmentManager());
mViewPager.setAdapter(swipeAdapter);
}
}
public class PageFragment extends android.support.v4.app.Fragment {
TextView textView;
String pageData[];
int position;
public PageFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view=inflater.inflate(R.layout.page_fragment_layout,container,false);
pageData=getResources().getStringArray(R.array.desserts);
textView=((TextView)view.findViewById(R.id.textView));
textView.setText(pageData[position]);
return view;
}
}
public class SwipeAdapter extends FragmentStatePagerAdapter{
public SwipeAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
Fragment fragment=new PageFragment();
return fragment;
}
@Override
public int getCount() {
return 9;
}
}
答案 0 :(得分:0)
public class MainActivity extends FragmentActivity {
ViewPager mViewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mViewPager = (ViewPager) findViewById(R.id.pager);
SwipeAdapter swipeAdapter=new SwipeAdapter(getSupportFragmentManager());
mViewPager.setAdapter(swipeAdapter);
}
}
public class PageFragment extends android.support.v4.app.Fragment {
TextView textView;
String pageData[];
int position;
public PageFragment() {
// Required empty public constructor
}
public PageFragment(int position) {
this.position = position;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view=inflater.inflate(R.layout.page_fragment_layout,container,false);
pageData=getResources().getStringArray(R.array.desserts);
textView=((TextView)view.findViewById(R.id.textView));
textView.setText(pageData[position]);
return view;
}
}
public class SwipeAdapter extends FragmentStatePagerAdapter{
public SwipeAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
Fragment fragment=new PageFragment(position);
return fragment;
}
@Override
public int getCount() {
return 9;
}
}