Android Viewpager在首次加载时显示错误的数据

时间:2015-03-07 07:18:44

标签: android android-fragments tabs android-viewpager android-tabhost

/ **我正在使用带有tabhost的android.support.v4.view.ViewPager来显示标签数据,我有3个标签 当第一次加载时,第一个选项卡加载第三个选项卡数据...第三个选项卡加载第一个选项卡数据。第二个选项卡正确加载自己的数据

我的代码对于viewpager和tabhost是Thx in Advance ** /

private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private String[] tabsTitles = {"SELL", "RENT", "PROJECT"};

viewPager = (ViewPager) findViewById(R.id.pager);
        mAdapter = new TabsPagerAdapter(getSupportFragmentManager(), tabsTitles.length);
        viewPager.setAdapter(mAdapter);

        final TabHost tabHost=(TabHost)findViewById(android.R.id.tabhost);
        tabHost.setup();

        for (int i = 0; i < tabsTitles.length; i++) {
            String tabName = tabsTitles[i];
            TabHost.TabSpec spec=tabHost.newTabSpec(tabName);
            spec.setContent(R.id.fakeTabContent);
            spec.setIndicator(tabName);
            tabHost.addTab(spec);
        }
        tabHost.setOnTabChangedListener(new OnTabChangeListener() {

            @Override
            public void onTabChanged(String tabId) {
                for (int i = 0; i < tabsTitles.length; i++) {
                    if (tabId.equals(tabsTitles[i])) {
                        viewPager.setCurrentItem(i);
                        break;
                    }
                }
            }
        });

viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageSelected(int position) {
                Toast.makeText(getApplicationContext(), String.valueOf(position), Toast.LENGTH_LONG).show();
                tabHost.setCurrentTab(position);
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onPageScrollStateChanged(int arg0) {
                // TODO Auto-generated method stub

            }
        });

1 个答案:

答案 0 :(得分:1)

适配器代码中存在问题

public Fragment getItem(int index) { 
    switch (index % 3) {
     case 2: // Top Rated fragment activity return
     new ProjectFragment(); 
    case 1: // Games fragment activity 
    return new RentFragment(); 
    case 0: // Movies fragment activity
     return new SellFragment();
     } return null; 
    }