Activity nest multiple Fragment to implement horizontal/vertical screen switching and activityfragment

Source: Internet
Author: User

Activity nest multiple Fragment to implement horizontal/vertical screen switching and activityfragment

I,

Ii. Requirements

Recently, the project encountered a problem of horizontal and vertical screen switching, which is complicated.

1. Three Fragment sets are nested in the vertical screen of the Activity. This article is short for vertical screen FP1, FP2, FP3.

2. the FP1 and FP2 of the portrait screen can be switched to FL1 and FL2 of the horizontal screen, that is, FP1 of the portrait screen switches to FL1 of the corresponding horizontal screen, and FP2 of the portrait screen switches to FL2 of the horizontal screen.

3. FP3 does not allow horizontal and vertical screen switching.

4. Landscape FP1, FP2, and FP3 use ViewPager to implement sliding switching between left and right.

5. FL1 and FL2 on the horizontal screen are switched between left and right using the switch button in the layout. Sliding switching is not allowed.


We can see that this requirement is a bit confusing !!! Haha !!!

(1) Let's Talk About the detours I 've taken and switch the landscape and landscape to an Activity.

(1) Where is it difficult to implement horizontal/vertical screen switching in an Activity? It mainly refers to screen switching. Activity has its own lifecycle, Fragment also has its own lifecycle, and the lifecycle of Activity is around Fragment. The most complicated part is that the onDestory () method of the Activity will be executed when the screen is switched for the first time. Before the method is executed, the onDestoryView () method of Fragment will be executed first, the onCreateView () method is executed. When you switch to the horizontal screen for the first time, the onCreate () method of the Activity will be executed, and the onCreateView () method of the FL1 horizontal screen will be executed again. In this way, the Fragment layout will be overwritten. (This is a problem I found when I was doing it. I don't know if anyone else has encountered it ).

(2) switching between landscape and landscape screens in an Activity. The landscape layout is different from the landscape layout. In this example, three Fragment entries are nested in the Activity, and two Fragment entries are nested in the landscape screen, first, there will be many page states to be recorded, followed by the issue of the lifecycle relationship between the Activity and Fragment, which is indeed complicated. To control the status, only people who have done it know how bitter it is.

(2) It is recommended to switch the screen between the two activities.


Iii. Solution

1. First of all, it is necessary to enable horizontal and vertical switch between the two activities. here we need to configure the two activities in AndroidManifest. xml to enable horizontal and vertical switch. The configuration is as follows:

<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. When the vertical screen Activity is switched to the horizontal screen Activity, the Intent is used to jump to the horizontal screen Activity, and the current Activity is sent to finish. The opposite is true. So what is a problem, where the jump is written, and what is written in the onDestory () method is obviously not suitable, because this method will always be executed during the vertical and vertical cutting, when you press the rollback key to return to the previous page, this method will also be executed. In this way, the page will always open in an endless loop. At this time, I thought of the onConfigurationChanged () method of the Activity. The Google official website said that you do not want to use this method to implement horizontal and vertical screen switching, but you have to use this strange demand. Code:

@Overridepublic void onConfigurationChanged(Configuration newConfig) {super.onConfigurationChanged(newConfig);ActivityLand.showActivityLand(this);finish();}

3. After switching between the two activities, we get a benefit. The Fragment lifecycle is very well controlled, and the logic in it can be written as needed. After switching, the layout will automatically load the layout of the horizontal screen. (I believe everyone understands what I mean ).


4. Switch to the corresponding Fragment, mainly by using the cache to record the page status. For details, see the source code.


5. Main Code:

(1) Main logic of the vertical screen 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";/** page type-landscape 1 **/public static final int PORT_PAGE_1 = 1; /** page type-Portrait screen 2 **/public static final int PORT_PAGE_2 = 2;/** page type-Portrait Screen 3 **/public static final int PORT_PAGE_3 = 3; private ViewPager vpChartPage; private Fragment1 fragment1; private Fragment2 fragment2; private Fragment3 fragment3;/** portrait FragmentManager **/private FragmentManager overview;/** manual **/private temporary details; /** Fragment set **/private List <Fragment> mFragmentList;/** time-sharing, key-line, and details interface adapter **/private ChartFragmentPagerAdapter mPagerAdapter; /** the screen direction is set to portrait by default **/private int mScreenOrientation = Configuration. ORIENTATION_PORTRAIT;/** current Fragment **/private Fragment mCurentFragment; public static void showActivityPort (Activity activity) {Intent intent Intent = new Intent (activity, ActivityPort. class); activity. startActivity (intent) ;}@ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. layout_main); mScreenOrientation = getResources (). getConfiguration (). orientation; portfragmentManager = getsuppfrfragmentmanager (); mFragmentTransaction = portfragmentManager. beginTransaction (); switch (mScreenOrientation) {case Configuration. ORIENTATION_PORTRAIT: // point-of-use 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); // horizontal 1 to vertical 1 to vertical 2 to vertical 2 to complete the horizontal and vertical switch of the corresponding page 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) ;}/ ** time-sharing, line-length, and detail portrait interface switching **/class ChartPageChangeListener implements ViewPager. onPageChangeListener {@ Overridepublic void publish (int I) {}@ Overridepublic void onPageScrolled (int I, float v, int i2) {}@ Overridepublic void onPageSelected (int I) {// set the interface indicator switch (I) {case 0: mCurentFragment = fragment1; setPageType (PORT_PAGE_1); break; case 1: setPageType (PORT_PAGE_2); mCurentFragment = fragment2; setRequestedOrientation (ActivityInfo. SCREEN_ORIENTATION_SENSOR); // you can set the break to be switched either horizontally or vertically. case 2: setPageType (PORT_PAGE_3); mCurentFragment = fragment3; setRequestedOrientation (ActivityInfo. SCREEN_ORIENTATION_PORTRAIT); // disable break rotation on the screen; }}@ Overridepublic void onConfigurationChanged (Configuration newConfig) {super. onConfigurationChanged (newConfig); ActivityLand. showActivityLand (this); finish () ;}@ Overrideprotected void onDestroy () {super. onDestroy () ;}@ Overridepublic boolean onKeyDown (int keyCode, KeyEvent event) {if (keyCode = KeyEvent. KEYCODE_BACK) {finish ();} return true;}/** record the current page type **/private void setPageType (int chartPageType) {DataCache. instance (). setmChartPageType (chartPageType);}/** get the current page type **/private int getPageType () {return DataCache. instance (). getmChartPageType ();}}


(2) Main logic of landscape 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";/** page type-landscape 1 **/public static final int LAND_PAGE_1 = 4; /** page type-landscape screen 2 **/public static final int LAND_PAGE_2 = 5; private Fragment1 fragment1; private Fragment2 fragment2; /** FragmentManager **/private FragmentManager mfragmentManager;/** fragmentTransaction **/private FragmentTransaction mFragmentTransaction; /** the screen direction is set to portrait by default **/private int mScreenOrientation = Configuration. ORIENTATION_PORTRAIT;/** current Fragment **/private Fragment mCurentFragment;/** switch Button **/private Button btSwitch; public static void showActivityLand (Activity activity) {Intent intent = new Intent (activity, ActivityLand. class); activity. startActivity (intent) ;}@ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. layout_main); mScreenOrientation = getResources (). getConfiguration (). orientation; mfragmentManager = getsuppfrfragmentmanager (); mFragmentTransaction = mfragmentManager. beginTransaction (); switch (mScreenOrientation) {case Configuration. ORIENTATION_LANDSCAPE: // X-axis 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 (); // horizontal 1 to vertical 1 to vertical 2 to vertical 2 to complete the horizontal and vertical switch of the corresponding page 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 ();}/*** horizontal screen switch * @ author Wilson */class implements OnClickListener {@ Overridepublic void onClick (View v) {if (mCurentFragment instanceof Fragment1) {// chunk 1 to chunk 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 to 1 mCurentFragment = fragment1; setPageType (LAND_PAGE_1); mFragmentTransaction = mfragmentManager. beginTransaction (); mFragmentTransaction. replace (R. id. ll_content, fragment1); mFragmentTransaction. commit () ;}}@ Overridepublic void onConfigurationChanged (Configuration newConfig) {super. onConfigurationChanged (newConfig); ActivityPort. showActivityPort (this); finish () ;}@ Overrideprotected void onDestroy () {super. onDestroy () ;}@ Overridepublic boolean onKeyDown (int keyCode, KeyEvent event) {if (keyCode = KeyEvent. KEYCODE_BACK) {finish ();} return true;}/** record the current page type **/private void setPageType (int chartPageType) {DataCache. instance (). setmChartPageType (chartPageType);}/** get the current page type **/private int getPageType () {return DataCache. instance (). getmChartPageType ();}}


6. Download link of sample code

Http://download.csdn.net/detail/xiogjie_67/8839853






























Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.