视图页面碎片随着时间的推移而被摧毁?
我正在使用Android的软件包来开发一个包含多个s的ViewPager。support.v4
Fragment
我正在尝试在用户更改页面时隐藏视图。因此,我实现了一个来监听我的适配器,并在发生页面更改时调用一个方法。但是我得到了一个,我不知道为什么。OnPageChangeListener
update()
Fragment
NullPointerException
代码如下:
public class MyActivity extends FragmentActivity implements
OnPageChangeListener {
private static final int NUM_ITEMS = 2;
private ViewPager mPager;
private static SpaceAdapter mAdapter;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_pager);
mAdapter = new SpaceAdapter(getSupportFragmentManager());
mPager = (ViewPager) findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
mPager.setOnPageChangeListener(this);
}
public static class SpaceAdapter extends FragmentPagerAdapter {
public SpaceAdapter(FragmentManager fm) {
super(fm);
}
@Override
public int getCount() {
return NUM_ITEMS;
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new MyFragment();
case 1:
return new MyFragment();
default:
return new MyFragment();
}
}
}
@Override
public void onPageScrollStateChanged(int arg0) {
Log.i("pagination", "scroll state changed: " + arg0);
}
@Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// Log.i("pagination", "page scroll: " + arg0 + " with: " + arg1 + ", " + arg2);
if (mAdapter.getItem(arg0) instanceof IUpdateOnPage) {
((IUpdateOnPage) mAdapter.getItem(arg0)).updateOnPage();
}
}
@Override
public void onPageSelected(int arg0) {
Log.i("pagination", "page selected: " + arg0);
}
}
和
public class MyFragment extends Fragment implements
SurfaceHolder.Callback, IUpdateOnPage {
private SurfaceView charts;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.crew, null);
bindViews(v);
return v;
}
private void bindViews(View v) {
charts = (SurfaceView) v.findViewById(R.id.civ_charts);
charts.getHolder().addCallback(this);
Log.i("wtf", "huh " + String.valueOf(charts == null)); // logs false
}
@Override
public void updateOnPage() {
if (charts != null) {
Log.i("crew surface", "hidden");
charts.setVisibility(View.GONE);
} else {
Log.i("crew surface", "charts is null"); //THIS HERE gets logged
}
}
}
当我复制/粘贴时,我删除了这些方法,但它们就在那里。该方法记录 if ,并且该方法始终返回 false。当我分页时,被调用,并返回 true。为什么会发生这种情况,我该如何解决这个问题?SurfaceHolder.Callback
bindViews(v)
charts == null
updateOnPage
charts == null
这是第108行:
charts.setVisibility(View.GONE);