使用FragmentPagerAdapter的Viewpager有3个片段

时间:2017-01-15 10:34:22

标签: android android-fragments android-viewpager

我使用ViewPager和3个片段编写了一个程序。我的问题是:

创建活动时,首先调用2个片段。从片段1到2时,单击或滚动片段2时,将调用片段3的onCreateView()方法。并且,当我从片段3向后移动到片段2到片段1时,public class ViewPagerAdapter extends FragmentPagerAdapter { private static int NUM_ITEMS = 3; Context context; public ViewPagerAdapter(FragmentManager manager,Context context) { super(manager); this.context = context; } @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: return Fragment_About.newInstance("About",20); case 1: return Fragment_EditSkills.newInstance ("Skills",30); case 2: return Fragment_EditActivities.newInstance("Activities",40); default: return null; } } } 方法被调用。

我的代码:

ViewPagerAdapter.java

public class Fragment_About extends Fragment {

public static Fragment_About newInstance(String name, int age) {
    Bundle bundle = new Bundle();
    bundle.putString("name", name);
    bundle.putInt("age", age);

    Fragment_About fragment = new Fragment_About();
    fragment.setArguments(bundle);

    Log.i("FragmentAbout instance","instance");
    Log.i("name",""+name);
    Log.i("age",""+age);
    return fragment;
}

private void readBundle(Bundle bundle) {
    if (bundle != null) {
        name = bundle.getString("name");
        age = bundle.getInt("age");
        Log.i("readBundle oncreateview","readBundle oncreateview");
        Log.i("name",""+name);
        Log.i("age",""+age);
    }
}

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup 
    container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_about, container, 
    false);

    txtEditAbout = (TextView) view.findViewById(R.id.textEditAbout);
    about = (TextView) view.findViewById(R.id.about);

    readBundle(getArguments());

}
}

Fragment_About.java

// when the activity is created.
I/FragmentAbout instance: instance
I/EditSkills instance: instance


// When I click on page 2
I/FragActivity instance: instance

日志:

newInstance()

从3向后移动到片段2到片段1被调用,但这次没有为任何片段调用I/readBundle oncreateview: readBundle oncreateview

System.out.printf("The Sum is %d%n" , sum);

请解释上述过程。

1 个答案:

答案 0 :(得分:0)

Viewpager根据 OffscreenPageLimit 参数预加载邻居片段。默认情况下,它设置为1( DEFAULT_OFFSCREEN_PAGES = 1)

您使用了 FragmentPagerAdapter ,这意味着如果片段视图远离屏幕外限制,则可以销毁它。