PagerAdapter问题与android Fragment

时间:2015-08-19 10:02:18

标签: android fragment android-pageradapter

我在PagerAdapter中遇到一个问题,当我在其中加载TextView时,它的完美代码如下:

@Override
public Object instantiateItem(ViewGroup container, int position) {
    LayoutInflater inflater = (LayoutInflater) mActivity
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View view = inflater.inflate(R.layout.test, container, false);

    TextView tv = (TextView) view.findViewById(R.id.tvtest);
    tv.setText("" + position);

    container.addView(view);
    return view;
}

当我使用Fragment代替TextView时,如下面的代码PagerAdapter中只加载第一个片段。 请帮我解决这个问题。

@Override
public Object instantiateItem(ViewGroup container, int position) {

    LayoutInflater inflater = (LayoutInflater) mActivity
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View view = inflater.inflate(R.layout.test, container, false);

    MyFragment fragment = new MyFragment ();
    FragmentTransaction transaction = mActivity.getFragmentManager().beginTransaction();
    transaction.add(R.id.fragment_container, fragment).commit();

    container.addView(view);

    return view;
}

XML代码:

使用TextView时

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/tvtest"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="Test"
android:textSize="30sp" />

使用片段时

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />

谢谢。

1 个答案:

答案 0 :(得分:3)

只需使用FragmentPagerAdapter而不是PagerAdapter。

public static class MyPagerAdapter extends FragmentPagerAdapter {
    private static int NUM_ITEMS = 3;

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

    // Returns total number of pages
    @Override
    public int getCount() {
        return NUM_ITEMS;
    }

    // Returns the fragment to display for that page
    @Override
    public Fragment getItem(int position) {
        switch (position) {
        case 0: // Fragment # 0 - This will show FirstFragment
            return FirstFragment.newInstance(0, "Page # 1");
        case 1: // Fragment # 0 - This will show FirstFragment different title
            return FirstFragment.newInstance(1, "Page # 2");
        case 2: // Fragment # 1 - This will show SecondFragment
            return SecondFragment.newInstance(2, "Page # 3");
        default:
            return null;
        }
    }

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

}