3

我正在使用https://github.com/astuetz/PagerSlidingTabStripPagerSlidingTabStrip的库。我想在滚动时更改片段。我用下面的代码实现了这一点。ViewPager

MainActivity.java

public class MainActivity extends SherlockFragmentActivity {

private MyPagerAdapter adapter;
ViewPager pager;
private PagerSlidingTabStrip tabs;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    tabs = (PagerSlidingTabStrip) findViewById(R.id.tabs);
    pager = (ViewPager) findViewById(R.id.pager);
    adapter = new MyPagerAdapter(getSupportFragmentManager());

    pager.setAdapter(adapter);

    final int pageMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4, getResources()
            .getDisplayMetrics());
    pager.setPageMargin(pageMargin);

    tabs.setViewPager(pager);

}

public class MyPagerAdapter extends FragmentPagerAdapter {
    private final String[] TITLES = {"First","Second","Third"};
    private SherlockFragment[] fragments = new SherlockFragment[] { new FirstFragment(), new SecondFragment(), new ThirdFragment()};

    public MyPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return TITLES[position];
    }

    @Override
    public int getCount() {
        return TITLES.length;
    }

    @Override
    public Fragment getItem(int position) {
        return fragments[position];
    }

}
}

FirstFragment.java

public class FirstFragment extends SherlockFragment {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    final View v = inflater.inflate(R.layout.fragment_main, container, false);
    Toast.makeText(getSherlockActivity(), "This is from first", Toast.LENGTH_SHORT).show();
    return v;
}
}

SecondFragment.java

public class SecondFragment extends SherlockFragment {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    final View v = inflater.inflate(R.layout.fragment_main, container, false);
    Toast.makeText(getSherlockActivity(), "SecondFragment", Toast.LENGTH_SHORT).show();
    return v;
}
}

第三片段.java

public class ThirdFragment extends SherlockFragment {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    final View v = inflater.inflate(R.layout.fragment_main, container, false);
    Toast.makeText(getSherlockActivity(), "ThirdFragment", Toast.LENGTH_SHORT).show();
    return v;
}
}

我得到了三个片段,我正在用 Toasts 测试它们。

当应用程序使用 MainActivity 打开时,FirstFragment 附加到Activity,但它显示了两个 toast,一个来自 FirstFragment,另一个来自 SecondFragment,当我滚动到第二个选项卡时,它显示了 ThirdFragment 的 toast。

所以,我想它会这样。如果我从左向右滚动,则显示当前片段右侧的片段,如果我从右向左滚动,则显示当前片段左侧的片段。请帮忙。

谢谢。

4

1 回答 1

2

这是因为片段缓存。当您访问一些片段时,它的兄弟片段也会被创建(调用 onCreate())。

于 2013-06-07T21:07:21.133 回答