我想在用户更改过滤器选项时更改片段的适配器(在本例中为学期)。
这是我的活动:
以下代码在第一时间正常工作:
我的活动处理学期更改
protected void onChangeSemester(String oldSemester, String newSemester) {
super.onChangeSemester(oldSemester, newSemester);
if (!oldSemester.equals(newSemester)) {
pagerAdapter.setSemester(newSemester);
}
}
然后我的 pagerAdapter ...
public void setSemester(String newSemester) {
gradesFragment.changeSemester(newSemester, context);
}
最后,我的片段:
public void changeSemester(String newSemester, Context context) {
this.context = context;
this.semester = newSemester;
if (adapter == null) {
adapter = createAdapter(newSemester);
setListAdapter(adapter);
}
adapter.setList(createList(newSemester));
}
然后我的适配器在changeSemester中重新创建,但数据没有更新。 我已经尝试过 getListView :
public void changeSemester(String newSemester, Context context) {
this.context = context;
this.semester = newSemester;
if (adapter == null) {
adapter = (GradeListAdapter) getListView().getAdapter();
}
adapter.setList(createList(newSemester));
}
但它抛出:
FATAL EXCEPTION: main java.lang.IllegalStateException: Content view not yet created
at android.support.v4.app.ListFragment.ensureList(ListFragment.java:328)
at android.support.v4.app.ListFragment.getListView(ListFragment.java:222)
at si.unisanta.tcc.unisantaapp.application.fragments.grade.GradesFragment.changeSemester(GradesFragment.java:110)
at si.unisanta.tcc.unisantaapp.application.MainActivityPagerAdapter.setSemester(MainActivityPagerAdapter.java:40)
at si.unisanta.tcc.unisantaapp.application.MainActivity.onChangeSemester(MainActivity.java:210)
at si.unisanta.tcc.unisantaapp.application.AppCompatActivityToolbarBase$1$1.onClick(AppCompatActivityToolbarBase.java:64)
at com.android.internal.app.AlertController$AlertParams$3.onItemClick(AlertController.java:940)
我做错了什么?看起来ListView引用丢失并变为null, onCreateView 在我的片段中没有再次调用,那么应该做什么?有一种方法可以通过重新创建片段或其他东西来修复它吗?
答案 0 :(得分:0)
我通过不在适配器中保存实例来解决问题。
My FragmentPagerAdapter:
//More fields...
private Map<Integer, Fragment> pageReferenceMap = new HashMap<>();
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return ClassesFragment.newInstance();
case 1:
return TestsFragment.newInstance();
case 2:
return GradesFragment.newInstance(semester);
}
return null;
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
Fragment fragment = (Fragment)super.instantiateItem(container, position);
pageReferenceMap.put(position, fragment);
return fragment;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
super.destroyItem(container, position, object);
pageReferenceMap.remove(position);
}
public void setSemester(String newSemester) {
this.semester = newSemester;
Fragment gradesFragment = pageReferenceMap.get(GRADES_INDEX);
if (gradesFragment != null) {
((GradesFragment)gradesFragment).changeSemester(newSemester);
}
}
这就是诀窍