CastException:从ViewPager更新片段后

时间:2013-08-07 23:59:24

标签: android android-fragments android-viewpager notifydatasetchanged

我正在使用:

更新我的片段编号2
@Override
public int getItemPosition(Object object) {
    FragmentPage2 f = (FragmentPage2) object;
    if (f != null) {
        f.update();
    }
    return super.getItemPosition(object);
}

现在,当我在Fragment中添加和添加其他getItem(int position)时,一切似乎都正常。但是,当我运行mPager.getAdapter().notifyDataSetChanged();时,它会抛出我:

08-07 19:45:50.844: E/AndroidRuntime(17776): java.lang.ClassCastException: com.foodbuilder.FragmentPage1 cannot be cast to com.foodbuilder.FragmentPage2
08-07 19:45:50.844: E/AndroidRuntime(17776):    at com.foodbuilder.MainActivity$MyAdapter.getItemPosition(MainActivity.java:967)
08-07 19:45:50.844: E/AndroidRuntime(17776):    at android.support.v4.view.ViewPager.dataSetChanged(ViewPager.java:851)
08-07 19:45:50.844: E/AndroidRuntime(17776):    at android.support.v4.view.ViewPager$PagerObserver.onChanged(ViewPager.java:2772)
08-07 19:45:50.844: E/AndroidRuntime(17776):    at android.database.DataSetObservable.notifyChanged(DataSetObservable.java:37)
08-07 19:45:50.844: E/AndroidRuntime(17776):    at android.support.v4.view.PagerAdapter.notifyDataSetChanged(PagerAdapter.java:276)
08-07 19:45:50.844: E/AndroidRuntime(17776):    at com.foodbuilder.MainActivity.onDialogPositiveClick(MainActivity.java:888)
08-07 19:45:50.844: E/AndroidRuntime(17776):    at com.foodbuilder.TablesDialogFragment$2.onClick(TablesDialogFragment.java:57)
08-07 19:45:50.844: E/AndroidRuntime(17776):    at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:166)
` 

发生了什么事?非常感谢你。

1 个答案:

答案 0 :(得分:1)

@Override
public int getItemPosition(Object object) {
    if(object != null && object instanceof FragmentPage2){
        FragmentPage2 f = (FragmentPage2) object;
        f.update();        
    }
    return super.getItemPosition(object);
}

同样,您可以获取对象类并检查它是否可以从FragmentPage2.class分配:

if(object.getClass().isAssignalbeFrom(FragmentPage2.class))

这是因为你有不同的类继承FragmentgetItemPosition()不关心对象的类型,但你做的转换确实关心对象的类型。

希望它有所帮助。