我到处寻找,但在每个帖子中问题似乎都存在。我使用FragmentStatePageAdapter实现了一个viewpager。当片段在UI上正确显示时,当我尝试将值传递给片段时,应用程序崩溃,因为片段未初始化。要检查我在每个部分中放置一个日志,只显示第一个和第三个日志。这是我的代码。
代码
resultsList[[1]]$coefficients
resultsList[[1]]$r.squared
这是我的日志:
public class MainActivity extends FragmentActivity implements OnDataReceivedListener, OnStateChangedListener {
ViewPager viewPager;
PagerAdapter pagerAdapter;
private ImageView logo;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
logo = (ImageView)findViewById(R.id.logo);
viewPager = (ViewPager)findViewById(R.id.viewpager_first);
pagerAdapter= new PagerAdapter(getSupportFragmentManager(),3);
CircleIndicator indicator (CircleIndicator)findViewById(R.id.indicator);
viewPager.setAdapter(pagerAdapter);
indicator.setEnabled(true);
indicator.setViewPager(viewPager);
logo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
flipApi.startScan();
}
});
}
class PagerAdapter extends FragmentStatePagerAdapter {
int num;
public PagerAdapter(FragmentManager fm, int x) {
super(fm);
this.num=x;
}
public Fragment currentFragment;
@Override
public Fragment getItem(int position) {
//add new fragment here for homepage viewpager
switch (position) {
case 0:
currentFragment = new Calorie_Fragment();
Log.d("flip",1+"");
return currentFragment;
case 1:
currentFragment = new HeartRate_Fragment();
Log.d("flip",2+"");
return currentFragment;
case 2:
currentFragment = new Steps_Fragment();
Log.d("flip",3+"");
return currentFragment;
default:
return null;
}
}
@Override
public int getCount() {
return num;
}
public Fragment getCurrentFragment() {
return this.currentFragment;
}
}
}
答案 0 :(得分:2)
试试这个。 :)
class PagerAdapter extends FragmentStatePagerAdapter {
HeartRate_Fragment heartRate_fragment;
Calorie_Fragment calorie_fragment;
Steps_Fragment steps_fragment;
int num;
public PagerAdapter(FragmentManager fm, int x) {
super(fm);
this.num=x;
}
@Override
public Fragment getItem(int position) {
//add new fragment here for homepage viewpager
switch (position) {
case 0:
if(heartRate_fragment == null)
heartRate_fragment = new HeartRate_Fragment();
Log.d("flip",1+"");
return heartRate_fragment;
case 1:
if(calorie_fragment == null)
calorie_fragment = new Calorie_Fragment();
Log.d("flip",2+"");
return calorie_fragment;
case 2:
if(steps_fragment == null)
steps_fragment = new Steps_Fragment();
Log.d("flip",3+"");
return steps_fragment;
default:
return null;
}
}
@Override
public int getCount() {
return num;
}
public HeartRate_Fragment getHRFragment()
{
return heartRate_fragment;
}
public Calorie_Fragment getCalorie_fragment()
{
return calorie_fragment;
}
public Steps_Fragment getSteps_fragment()
{
return steps_fragment;
}