我正在尝试为应用创建布局,在纵向方向时使用ViewPager显示片段,在横向模式下并排显示。 所以我为横向模式创建了自定义布局,在那里包含了碎片并且有效,但只有当我旋转一次时才会这样。当我将其旋转回纵向模式,再次旋转到横向模式时,应用程序崩溃并且logcat给我错误:片段尚未附加。
MainActivity.java
public class MainActivity extends AppCompatActivity {
private static final String TAG="MainActivity";
private SectionsPageAdapter mSectionsPageAdapter;
private ViewPager mViewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG,"onCreate: Starging.");
if(getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
mSectionsPageAdapter = new SectionsPageAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.container);
setupViewPager(mViewPager);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
}
}
private void setupViewPager(ViewPager viewPager){
SectionsPageAdapter adapter = new SectionsPageAdapter(getSupportFragmentManager());
adapter.addFragment(new Fragment1(),"Zakladka1");
adapter.addFragment(new Fragment2(),"Zakladka2");
viewPager.setAdapter(adapter);
}
}
其中一个片段:
public class Tab_Sun extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (!isAdded()){return null;} ;
View rootView = inflater.inflate(R.layout.tabsun, container, false);
//AstroCalculator.Location pozycja;
//pozycja.setLatitude();
return rootView;
}
}
完整应用:https://www.dropbox.com/s/0zcu3y7ej1fa9on/MyApplication3.zip?dl=0