如何使用ViewPager切换到其他布局?

时间:2012-08-26 02:39:51

标签: android android-layout android-fragments android-viewpager fragmentpageradapter

    public class SectionsPagerAdapter extends FragmentPagerAdapter {

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

    @Override
    public Fragment getItem(int i) {
        Fragment fragment = new DummySectionFragment();
        Bundle args = new Bundle();
        args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, i + 1);
        fragment.setArguments(args);
        return fragment;
    }

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

    @Override
    public CharSequence getPageTitle(int position) {
        switch (position) {
            case 0: return getString(R.string.title_section1).toUpperCase();
            case 1: return getString(R.string.title_section2).toUpperCase();
            case 2: return getString(R.string.title_section3).toUpperCase();
        }
        return null;
    }
}

/**
 * A dummy fragment representing a section of the app, but that simply displays dummy text.
 */
public static class DummySectionFragment extends Fragment {
    public DummySectionFragment() {
    }

    public static final String ARG_SECTION_NUMBER = "section_number";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        TextView textView = new TextView(getActivity());
        textView.setGravity(Gravity.CENTER);
        Bundle args = getArguments();
        textView.setText(Integer.toString(args.getInt(ARG_SECTION_NUMBER)));
        return inflater.inflate(R.layout.fragment_content1, container, false);
    }
}
}

上面的代码是来自ViewPager SDK的模板,当我从一个页面滑动到一个页面时,它只放置文本1到3。问题是当我滑动它时如何替换该文本并放置我自己的布局xml,并且可以将WebView与此功能一起使用。例如:当活动加载时,它会转到google.com,然后当我滑动到其他页面时,每次刷卡时它都会更改WebView的URL?希望有人可以帮助我...

2 个答案:

答案 0 :(得分:1)

您必须创建从android.support.v4.app.Fragment扩展的类,就像类DummySectionFragment一样。然后,在方法getItem(int i)中,您应该为每个索引实例化所需的每个类,方法getCount()必须返回您要实例化的碎片数。

答案 1 :(得分:0)

viewpager.setCurrentItem(index)其中index是所需的片段索引。