1

我正在使用 aFragmentStatePagerAdapter为了达到一个VerticalPageAdapter目的,我必须创建一个动态编号的相同 Fragment 关于哪个Button被按下,所以,我只检索getItem()方法中的指定片段:

public Fragment getItem(int i) {            
  return new Center_ver();        
}

getCount()返回一个关于Button在其他片段中按下的动态数字:

@Override
public int getCount() {         
    return num_of_gangs;    
}

但这给了我IlligalStateException,因为我没有被调用notifyDataSetChanged(),所以,我将通知添加到我用来提高片段数量的方法中:

public void add_gang() {    
    num_of_gangs ++;
    notifyDataSetChanged();     
}

但我也得到了IlligalStateException

05-04 13:43:43.210: E/AndroidRuntime(1625): FATAL EXCEPTION: main
05-04 13:43:43.210: E/AndroidRuntime(1625): java.lang.IllegalStateException: The application's PagerAdapter changed the adapter's contents without calling PagerAdapter#notifyDataSetChanged! Expected adapter item count: 1, found: 5 Pager id: com.automation.isolace:id/lighting_vertical_pager Pager class: class com.automation.standards.VerticalViewPager Problematic adapter: class com.automation.pageadapters.LightVerticalPageAdapter

因此,我决定在返回 Value 之前将其添加到 getCount() 方法中,如下所示:

@Override
public int getCount() {     
    notifyDataSetChanged();
    return num_of_gangs ;    
}

但这给了我一个StackOverflowError

05-04 13:46:36.326: E/AndroidRuntime(1690): FATAL EXCEPTION: main
05-04 13:46:36.326: E/AndroidRuntime(1690): java.lang.StackOverflowError
05-04 13:46:36.326: E/AndroidRuntime(1690):     at com.automation.standards.VerticalViewPager$PagerObserver.onChanged(VerticalViewPager.java:2717)
05-04 13:46:36.326: E/AndroidRuntime(1690):     at android.database.DataSetObservable.notifyChanged(DataSetObservable.java:37)
05-04 13:46:36.326: E/AndroidRuntime(1690):     at android.support.v4.view.PagerAdapter.notifyDataSetChanged(PagerAdapter.java:276)
4

2 回答 2

1

你不应该放进notifyDataSetChanged()getCount()notifyDataSetChanged()调用getCount(),最终导致一个调用另一个的无限循环,称为 StackOverflow 错误。当您将数据添加到可能的结果列表中时,您应该调用它。例如,如果您要添加一个新的 Fragment,它可能存储在 ArrayList 中,您可以这样做:

public void add_gang(Fragment frag) {
    fragmentList.add(frag);
    notifyDataSetChanged();
}
于 2014-05-04T13:50:02.947 回答
0

This basically happens when the view that populates your elements feels that it has been cheated on. Checks for that are not done on a recurrent fashion, that's why you may get the exception occasionally. It's a way for the view to tell us that there's something wrong on with the way we notify the adapter, something that we've missed or don't want obviously.

This design glitch normally appears when using references for the list used by our adapter to populate our view. This, it's always a good simplification to host a list of objects in the same activity where your adapter and view live and update it through add/addAll/remove/removeAll. Don't forget to call notifyDataSetChanged after any of those.

于 2014-05-04T14:11:45.030 回答