ViewPager为所有页面显示相同的ListFragments

时间:2013-01-12 20:33:01

标签: android android-viewpager android-listfragment

我正在尝试使用FragmentPagerAdapter将ListFragment与ViewPager一起使用。寻呼机由ListFragment的两个实例组成。 ViewPager控件可以工作并允许我在片段之间滑动,但两个页面中都会出现相同的ListFragment。似乎ViewPager的getItem()方法创建了ListFragment的两个不同实例,但它只显示了两个页面的第二个实例。这是一个代码:

// FragmentPagerAdapter
private static class MyFragmentPagerAdapter extends FragmentPagerAdapter {      
    public MyFragmentPagerAdapter(FragmentManager fm)   {
        super(fm);
    }

    @Override
    public Fragment getItem(int index) {
        Log.i("Page: ", index + "");
        return PageFragment.newInstance(pages.get(index));
        // pages is an ArrayList<ArrayList<Restaurant>> pages
    }

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


// ListFragment
public class PageFragment extends ListFragment {

    private static ArrayList<Restaurant> restaurantsList;

    public static PageFragment newInstance(ArrayList<Restaurant> restaurantsList) {
        PageFragment pageFragment = new PageFragment();
        pageFragment.setRestaurantsList(restaurantsList);
        return pageFragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState); 
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)   {
    View view = inflater.inflate(R.layout.fragment, container, false);      
    setListAdapter(new RestaurantArrayAdapter(getActivity().getBaseContext(), getRestaurantsList()) );
    return view;
    }


    private void setRestaurantsList(ArrayList<Restaurant> list)
    {
        restaurantsList = list;
    }

    private ArrayList<Restaurant> getRestaurantsList()
    {
        return this.restaurantsList;
    }
}

1 个答案:

答案 0 :(得分:2)

好伙伴, 问题是你已经将数组成员声明为“静态”,

private static ArrayList<Restaurant> restaurantsList;

失去静电,你应该没事。