我有兩個片段:FirstFragment
和SecondFragment
。 FirstFragment
包含ViewPager
,它有三個頁面(三個片段)。在活動的onCreate
,在主佈局上添加FirstFragment
,3頁正常顯示。在Android中添加ViewPager in Fragment
問題是:當我用SecondFragment
替換FirstFragment
,然後復出FirstFragment
三頁消失。然後我滾動ViewPager
前進和後退,頁面顯示但只有第一和第三頁顯示,第二頁消失。
這裏FirstFragment
:
package com.example.bkmsx.afragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class FirstFragment extends Fragment {
ViewPager mViewPager;
static MainActivity mainActivity;
public static FirstFragment newInstance(MainActivity activity){
mainActivity = activity;
return new FirstFragment();
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.first_fragment, null);
mViewPager = (ViewPager) view.findViewById(R.id.view_pager);
ViewPagerAdapter adapter = new ViewPagerAdapter(mainActivity.getSupportFragmentManager());
mViewPager.setAdapter(adapter);
return view;
}
private class ViewPagerAdapter extends FragmentPagerAdapter {
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
String text = "";
switch (position) {
case 0: text = "First Page";
break;
case 1: text = "Second Page";
break;
case 2: text = "Third Page";
break;
}
return TextFragment.newInstance(mainActivity, text);
}
@Override
public int getCount() {
return 3;
}
}
}
SecondFragment
:
package com.example.bkmsx.afragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class SecondFragment extends Fragment {
static MainActivity mainActivity;
public static SecondFragment newInstance(MainActivity activity) {
mainActivity = activity;
return new SecondFragment();
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
TextView textView = new TextView(mainActivity);
textView.setText("New Fragment");
return textView;
}
}
任何sugg estion?提前致謝。
mViewPager.setOffscreenPageLimit(3); –