0
我寫了一個使用ViewPager和3片段的程序。我的問題是:Viewpager使用3片段使用FragmentPagerAdapter
當活動創建時,首先調用2個片段。當從片段1到片段2時,當片段2被點擊或滾動時,片段3的newInstance()
方法被調用。而且,當我從片段3向後移動到片段2時,片段1調用方法onCreateView()
。
我的代碼:
ViewPagerAdapter.java
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;
}
}
}
Fragment_About.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());
}
}
日誌:
// when the activity is created.
I/FragmentAbout instance: instance
I/EditSkills instance: instance
// When I click on page 2
I/FragActivity instance: instance
從3向後移動至片段2至fragmen噸1被稱爲但此時newInstance()
不要求任何片段
I/readBundle oncreateview: readBundle oncreateview
請說明上述處理的。
'getItem'總是在您的代碼中返回一個新實例。當您滑動時,下一個最接近的碎片將加載到內存中。你可以像陣列適配器那樣存儲Fragment對象列表 –