使用新内容从ViewPager更新ListFragment

时间:2015-05-17 17:52:25

标签: android android-fragments

现在,我创建了两个片段,一个是GoogleMap,另一个是listFragment。每2秒我从服务器获得更新信息,存储在一个数组中。我的问题是,如何强制更新我的列表片段与新信息显示? newInstance方法不起作用。这是我的代码:

public class MyPagerAdapter extends FragmentPagerAdapter {
    private int NUM_ITEMS = 2;

    public MyPagerAdapter(FragmentManager fragmentManager) {
        super(fragmentManager);
    }
    @Override
    public int getCount() {
        return NUM_ITEMS;
    }

    // Returns the fragment to display for that page
    @Override
    public android.support.v4.app.Fragment getItem(int position) {
        switch (position) {
            case 0: // Fragment # 0 - This will show FirstFragment
                return MapFragment.newInstance("Map");
            case 1:
                return new MyListFragment();
            default:
                return null;
        }
    }

    @Override
    public int getItemPosition(Object object) {
        return POSITION_NONE;
    }

    // Returns the page title for the top indicator
    @Override
    public CharSequence getPageTitle(int position) {
        return "Page " + position;
    }

}

第2部分中的位置1表示我想要更新的ListFragment

ViewPager vpPager = (ViewPager) findViewById(R.id.vpPager);
    adapterViewPager = new MyPagerAdapter(getSupportFragmentManager());
    vpPager.setAdapter(adapterViewPager);
    vpPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

        // This method will be invoked when a new page becomes selected.
        @Override
        public void onPageSelected(int position) {
            if(position==1){

            }
        }

        // This method will be invoked when the current page is scrolled
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            // Code goes here
        }

        // Called when the scroll state changes:
        // SCROLL_STATE_IDLE, SCROLL_STATE_DRAGGING, SCROLL_STATE_SETTLING
        @Override
        public void onPageScrollStateChanged(int state) {
            // Code goes here
        }
    });

1 个答案:

答案 0 :(得分:0)

使用此answer - 获取片段的引用并在onPageSelected方法中调用正确的方法(取决于您在ListFragment中的ListView中获取数据的实现)。