Activity嵌套多个Fragment实现横竖屏切换
一、上图
二、需求
近期项目遇到个横竖屏切换的问题,较为复杂,在此记之。
1、Activity中竖屏嵌套3个Fragment,本文简称竖屏FP1,FP2,FP3。
2、其中竖屏FP1与FP2可以切换为横屏的FL1,FL2,即竖屏FP1切换到对应的横屏FL1,竖屏FP2对应切换到横屏FL2。
3、FP3不允许横竖屏切换。
4、竖屏FP1,FP2,FP3用ViewPager实现左右滑动切换。
5、横屏的FL1,FL2用布局中的切换按扭实现左右切换,不允许滑动切换。
看到这需求有点儿晕菜了吧!!!呵呵!!!
(一)先说说我走过的弯路,将横竖屏切换在一个Activity中实现。
(1)、在一个Activity中实现横竖屏切换难在什么地方呢?主要是横竖屏切换,Activity有它自己的生命周期、Fragment也有它的生命周期,而且Activity的生命周期左右着Fragment的生命周期。最复杂的地方是,首次横竖屏切换时,Activity的onDestory()方法会执行,在执行此方法之前,Fragment的onDestoryView()首先会获得执行,接着会执行onCreateView()方法。而首次切换到横屏时,Activity的onCreate()方法会执行,接着横屏FL1的onCreateView()方法又会执行,这样的话,Fragment的布局就会发生覆盖。(这是我在做的时候发现的问题,不知道其他人是否遇到)。
(2)、在一个Activity中横竖屏切换,竖屏布局与横屏布局不一样,本文示例竖屏为Activity中嵌套3个Fragment,横屏嵌套2个Fragment,首先会有很多页面状态需要记录,其次就是Activity与Fragment的生命周期关系问题,确实挺复杂,控制这里面的状态,只有做过的人才知道有多苦。
(二)可取的办法,将横竖屏切换在两个Activity中实现
三、解决问题思路
1、首先当然是要让两个Activity能够横竖切,这里首先需要在AndroidManifest.xml中配置两个Activity能够横竖切换,配置如下:
<activity android:name=".ActivityPort" android:configChanges="orientation|keyboardHidden|screenSize" android:label="@string/app_name" android:windowSoftInputMode="stateAlwaysHidden|adjustPan" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".ActivityLand" android:configChanges="orientation|keyboardHidden|screenSize" android:label="@string/app_name" android:windowSoftInputMode="stateAlwaysHidden|adjustPan" />
2、竖屏Activity的切换到横屏Activity的时候,通过Intent跳转到横屏的Activity,然后将当前Activity给finish()掉。反之也是一样的逻辑。那么现在面临的一个问题是什么,这个跳转写在什么地方,写在onDestory()方法中显然是不合适的,因为这个方法在横竖切的时候会始终执行,当你在按回退键返回到上一个页面时,同样会执行这个方法,这样跳转的话,就会死循环,会总是打开页面。这时候就想到了Activity的onConfigurationChanged()方法。Google官网说横竖屏切换不希望大家用这个方法实现横竖屏切换,但是遇到了这样怪异的需求,不得不使用。上代码:
@Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); ActivityLand.showActivityLand(this); finish(); }
3、在两个Activity中实现横竖切换之后,换来一个好处,Fragment的生命周期我们非常好控制,里面的逻辑相怎么写就怎么写,而且切换过来之后,布局也会自动去加载横屏的布局。(相信大家明白我的意思)。
4、切换到对应的Fragment,主要是借助于缓存,记录页面状态。详见源码。
5、上主要代码:
(1)竖屏Activity的主要逻辑
package com.example.screenswitch; import java.util.ArrayList; import java.util.List; import android.app.Activity; import android.content.Intent; import android.content.pm.ActivityInfo; import android.content.res.Configuration; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v4.view.ViewPager; import android.view.KeyEvent; import com.example.screenswitch.adapter.ChartFragmentPagerAdapter; import com.example.screenswitch.application.DataCache; import com.example.screenswitch.fragments.Fragment1; import com.example.screenswitch.fragments.Fragment2; import com.example.screenswitch.fragments.Fragment3; public class ActivityPort extends FragmentActivity { private static final String TAG = "ActivityPort"; /**页面类型-竖屏1**/ public static final int PORT_PAGE_1 = 1; /**页面类型-竖屏2**/ public static final int PORT_PAGE_2 = 2; /**页面类型-竖屏3**/ public static final int PORT_PAGE_3 = 3; private ViewPager vpChartPage; private Fragment1 fragment1; private Fragment2 fragment2; private Fragment3 fragment3; /**竖屏FragmentManager**/ private FragmentManager portfragmentManager; /**fragmentTransaction**/ private FragmentTransaction mFragmentTransaction; /**Fragment集合**/ private List<Fragment> mFragmentList; /**分时、K线、明细界面适配器**/ private ChartFragmentPagerAdapter mPagerAdapter; /**屏幕方向 默认指定为竖屏**/ private int mScreenOrientation = Configuration.ORIENTATION_PORTRAIT; /**当前Fragment**/ private Fragment mCurentFragment; public static void showActivityPort(Activity activity){ Intent intent = new Intent(activity,ActivityPort.class); activity.startActivity(intent); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.layout_main); mScreenOrientation = getResources().getConfiguration().orientation; portfragmentManager = getSupportFragmentManager(); mFragmentTransaction = portfragmentManager.beginTransaction(); switch (mScreenOrientation) { case Configuration.ORIENTATION_PORTRAIT:// 竖屏 分时 K线 findPortViews(); initPortCtrl(); break; } } private void findPortViews(){ vpChartPage = (ViewPager) findViewById(R.id.vp_chart_page); vpChartPage.setOnPageChangeListener(new ChartPageChangeListener()); } private void initPortCtrl(){ fragment1 = new Fragment1(); fragment2 = new Fragment2(); fragment3 = new Fragment3(); mFragmentList = new ArrayList<Fragment>(); mFragmentList.add(fragment1); mFragmentList.add(fragment2); mFragmentList.add(fragment3); mCurentFragment = fragment1; mPagerAdapter = new ChartFragmentPagerAdapter(portfragmentManager,mFragmentList); vpChartPage.setAdapter(mPagerAdapter); //横1对竖1 横2对竖2 完成对应页的横竖切换 if(getPageType() == PORT_PAGE_1 || getPageType() == ActivityLand.LAND_PAGE_1){ setPageType(PORT_PAGE_1); vpChartPage.setCurrentItem(0); }else if(getPageType() == PORT_PAGE_2 || getPageType() == ActivityLand.LAND_PAGE_2){ setPageType(PORT_PAGE_2); vpChartPage.setCurrentItem(1); } } /**分时、K线、明细竖屏界面切换**/ class ChartPageChangeListener implements ViewPager.OnPageChangeListener { @Override public void onPageScrollStateChanged(int i) { } @Override public void onPageScrolled(int i, float v, int i2) { } @Override public void onPageSelected(int i) { //设置界面指示器 switch (i) { case 0: mCurentFragment = fragment1; setPageType(PORT_PAGE_1); break; case 1: setPageType(PORT_PAGE_2); mCurentFragment = fragment2; setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);//设置可以横竖切换 break; case 2: setPageType(PORT_PAGE_3); mCurentFragment = fragment3; setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//禁止屏幕旋转 break; } } } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); ActivityLand.showActivityLand(this); finish(); } @Override protected void onDestroy() { super.onDestroy(); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if(keyCode == KeyEvent.KEYCODE_BACK){ finish(); } return true; } /**记录当前页面类型**/ private void setPageType(int chartPageType) { DataCache.instance().setmChartPageType(chartPageType); } /**获取当前页面类型 **/ private int getPageType() { return DataCache.instance().getmChartPageType(); } }
(2)、横屏Activity的主要逻辑
package com.example.screenswitch; import android.app.Activity; import android.content.Intent; import android.content.res.Configuration; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.view.KeyEvent; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import com.example.screenswitch.application.DataCache; import com.example.screenswitch.fragments.Fragment1; import com.example.screenswitch.fragments.Fragment2; public class ActivityLand extends FragmentActivity { private static final String TAG = "ActivityLand"; /**页面类型-横屏1**/ public static final int LAND_PAGE_1 = 4; /**页面类型-横屏2**/ public static final int LAND_PAGE_2 = 5; private Fragment1 fragment1; private Fragment2 fragment2; /**竖屏FragmentManager**/ private FragmentManager mfragmentManager; /**fragmentTransaction**/ private FragmentTransaction mFragmentTransaction; /**屏幕方向 默认指定为竖屏**/ private int mScreenOrientation = Configuration.ORIENTATION_PORTRAIT; /**当前Fragment**/ private Fragment mCurentFragment; /**切换按钮**/ private Button btSwitch; public static void showActivityLand(Activity activity) { Intent intent = new Intent(activity, ActivityLand.class); activity.startActivity(intent); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.layout_main); mScreenOrientation = getResources().getConfiguration().orientation; mfragmentManager = getSupportFragmentManager(); mFragmentTransaction = mfragmentManager.beginTransaction(); switch (mScreenOrientation) { case Configuration.ORIENTATION_LANDSCAPE:// 横屏 分时 K线 findLandViews(); initLandCtrl(); break; } } private void findLandViews() { btSwitch = (Button) findViewById(R.id.bt_switch); btSwitch.setOnClickListener(new TheOnSwitchBtnClickListener()); } private void initLandCtrl() { fragment1 = new Fragment1(); fragment2 = new Fragment2(); //横1对竖1 横2对竖2 完成对应页的横竖切换 if (getPageType() == ActivityPort.PORT_PAGE_1 || getPageType() == LAND_PAGE_1) { setPageType(ActivityPort.PORT_PAGE_1); mCurentFragment = fragment1; } else if (getPageType() == ActivityPort.PORT_PAGE_2 || getPageType() == LAND_PAGE_2) { setPageType(ActivityPort.PORT_PAGE_2); mCurentFragment = fragment2; } mFragmentTransaction = mfragmentManager.beginTransaction(); mFragmentTransaction.add(R.id.ll_content, mCurentFragment); mFragmentTransaction.commit(); } /** * 横屏界面切换 * @author Wilson */ class TheOnSwitchBtnClickListener implements OnClickListener { @Override public void onClick(View v) { if (mCurentFragment instanceof Fragment1) {//横1切到横2 mCurentFragment = fragment2; setPageType(LAND_PAGE_2); mFragmentTransaction = mfragmentManager.beginTransaction(); mFragmentTransaction.replace(R.id.ll_content, fragment2); mFragmentTransaction.commit(); } else if (mCurentFragment instanceof Fragment2) {//横2切到横1 mCurentFragment = fragment1; setPageType(LAND_PAGE_1); mFragmentTransaction = mfragmentManager.beginTransaction(); mFragmentTransaction.replace(R.id.ll_content, fragment1); mFragmentTransaction.commit(); } } } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); ActivityPort.showActivityPort(this); finish(); } @Override protected void onDestroy() { super.onDestroy(); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { finish(); } return true; } /**记录当前页面类型**/ private void setPageType(int chartPageType) { DataCache.instance().setmChartPageType(chartPageType); } /**获取当前页面类型 **/ private int getPageType() { return DataCache.instance().getmChartPageType(); } }