Android learning 8 (use of android fragment)
Fragment is a type of UI Fragment that can be embedded in an activity. It allows programs to make more reasonable and full use of the screen space. First, create a flat simulator 1034*600 and use android4.2.2. create an android project named FragmentTest.
Simple use of fragments
The following code creates a left-side fragment layout left_fragment.xml:
This layout value is placed with a button and displayed horizontally in the center. The code for creating a right-side layout right_fragment.xml is as follows:
The background color of the above layout is set to green, and a TextView is placed to display a piece of text. Create a new LeftFragment class that inherits from Fragment. Note that there may be two different Fragment packages for us to choose from. android is recommended. app. fragment, because our program is intended for Android or later systems, and the Fragment under another package is mainly used for compatibility with earlier Android systems. The LeftFragment code is as follows:
package com.wj.fragmenttest;import android.app.Fragment;import android.os.Bundle;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;public class LeftFragment extends Fragment {@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {// TODO Auto-generated method stubView view=inflater.inflate(R.layout.left_fragment,container, false);return view;}}
The code for creating a new RightFragment is as follows:
package com.wj.fragmenttest;import android.app.Fragment;import android.os.Bundle;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;public class RightFragment extends Fragment {@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {// TODO Auto-generated method stubView view=inflater.inflate(R.layout.right_fragment,container, false);return view;}}
The above code is too simple to be said.
Next, modify activity_main.xml. The Code is as follows:
The above Code uses the fragment label to add fragments to the layout.
Run the program. The result is as follows:
The above parts are added statically, so let's try to add them dynamically.
Create a layout file named another_right_fragment.xml. The Code is as follows:
Then create AnotherRightFragment as another right part. The Code is as follows:
package com.wj.fragmenttest;import android.app.Fragment;import android.os.Bundle;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;public class AnotherRightFragment extends Fragment {@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {// TODO Auto-generated method stubView view=inflater.inflate(R.layout.another_right_fragment,container, false);return view;}}
Next, modify the activity_main.xml file. The Code is as follows:
<framelayout android:id="@+id/right_layout" android:layout_height="match_parent" android:layout_weight="1" android:layout_width="0dp">
</framelayout>
The FrameLayout layout method is used here. In the subsequent code, we will replace the content in FrameLayout to dynamically add fragments. Modify the code in MainActivity:
Package com. wj. fragmenttest; import android. app. activity; import android. app. fragmentManager; import android. app. fragmentTransaction; import android. OS. bundle; import android. view. menu; import android. view. view; import android. view. view. onClickListener; import android. widget. button; public class MainActivity extends Activity implements OnClickListener {@ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); Button button = (Button) findViewById (R. id. button1); button. setOnClickListener (this) ;}@ Overridepublic boolean onCreateOptionsMenu (Menu menu) {// Inflate the menu; this adds items to the action bar if it is present. getMenuInflater (). inflate (R. menu. main, menu); return true ;}@ Overridepublic void onClick (View v) {// TODO Auto-generated method stubswitch (v. getId () {case R. id. button1: // create fragments AnotherRightFragment fragment = new shards (); // Get layout manager FragmentManager fragmentManager = getFragmentManager (); // get FragmentTransaction transaction = fragmentManager. beginTransaction (); // replace id with R. id. transaction in right_layout. replace (R. id. right_layout, fragment); transaction. commit (); // submit the transaction break; default: break ;}}}
Run the program:
Click the button on the left and the result is as follows:
It can be seen from the code that the dynamic addition of fragments is mainly divided into five steps.
1. Create the fragment instance to be added.
2. Get the FragmentManager. You can call the getFragmentManager () method in the activity to obtain it.
3. Enable a transaction by calling the beginTransaction () method.
4. Add fragments to the container. Generally, the replace () method is used. You need to input the container id and the fragment instance to be added.
5. commit the transaction and call the commit () method to complete it.
Simulate return stack in fragments
After you click the button to add a shard, press the back key to exit. If we want to simulate the effect similar to the returned stack, we can press the back key to return to the previous shard. How can we achieve this? See the following operations:
In fact, it is relatively simple. In FragmentTransaction, an addToBackStack () method is provided to add a transaction to the return stack. modify the code in MainActivity as follows:
Package com. wj. fragmenttest; import android. app. activity; import android. app. fragmentManager; import android. app. fragmentTransaction; import android. OS. bundle; import android. view. menu; import android. view. view; import android. view. view. onClickListener; import android. widget. button; public class MainActivity extends Activity implements OnClickListener {@ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); Button button = (Button) findViewById (R. id. button1); button. setOnClickListener (this) ;}@ Overridepublic boolean onCreateOptionsMenu (Menu menu) {// Inflate the menu; this adds items to the action bar if it is present. getMenuInflater (). inflate (R. menu. main, menu); return true ;}@ Overridepublic void onClick (View v) {// TODO Auto-generated method stubswitch (v. getId () {case R. id. button1: // create fragments AnotherRightFragment fragment = new shards (); // Get layout manager FragmentManager fragmentManager = getFragmentManager (); // get FragmentTransaction transaction = fragmentManager. beginTransaction (); // replace id with R. id. transaction in right_layout. replace (R. id. right_layout, fragment); transaction. addToBackStack (null); transaction. commit (); // submit the transaction break; default: break ;}}}
Here, the addToBackStack () method of FragmentManager is called before the transaction is committed. It can receive a name used to describe the status of the returned stack. Generally, null is passed in. Now rewrite the running program, click the button to add AnotherRightFragment to the activity, and then press the Back key. You will find that you have returned to the RightFragment interface, and then press the Back key again to exit.
Fragments and activities communicate directly
To facilitate direct communication between fragments and activities, FragmentManager provides a method similar to findViewById (), which is used to obtain fragments from the layout file. The Code is as follows:
RightFragment rightFragment = (RightFragment) getFragmentManager (). findFragmentById (R. id. right_fragment );
Call the findFragmentById method of FragmentManager to obtain the corresponding fragment instance in the activity, and then you can easily call the methods in the FragmentManager.
I learned how to call methods in fragments in an activity. How can I call methods in an activity in fragments?
You can call the getActivity () method in each fragment to obtain the activity instance associated with the current fragment. The Code is as follows:
MainActivity mainActivity = (MainActivity) getActivity ();
With an active instance, it is easy to call the methods in the activity in the fragment. In addition, you can also use the getActivity () method when the Context object needs to be used in the fragment, because the activity itself is a Context object.
Fragment Lifecycle
Like an activity, fragments also have their own lifecycles.
Running status: When a fragment is visible and its associated activity is running, the fragment is also running.
Paused: when an activity enters the paused state (because another activity that is not fully occupied by the screen is added to the top of the stack), the visible fragments associated with the activity will enter the paused state.
Stop status: when an activity is in the stopped status, the fragments associated with it enter the stopped status. You can also use the remove and replace methods of FragmentTransaction to remove fragments from the activity. However, if you call the addToBackStack () method before the transaction is committed, the fragments also enter the stop state. In general, fragments in the Stop State are completely invisible to users and may be recycled.
Destruction status: fragments are always attached to activities. Therefore, when an activity is revoked, the fragments associated with the activity enter the destruction status. Or by calling the remove of FragmentTransaction, the replace method removes fragments from the activity, but the addToBackStack () method is not called before the transaction is committed, and the fragments also enter the destruction state.
Several important fragmentation return methods:
1. onAttach (): called when fragments and activities are associated.
2. onCreateView (): called when a view (loading layout) is created for the shard
3. onActivityCreated (): Make sure that the activity associated with the fragment is called when it is created.
4. onDestroyView (): called when the view associated with the Shard is removed.
5. onDetach (): called when fragments and activities are unbound
Is the lifecycle diagram of a shard:
Modify the code in RightFragment. The Code is as follows:
package com.wj.fragmenttest;import android.app.Activity;import android.app.Fragment;import android.os.Bundle;import android.util.Log;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;public class RightFragment extends Fragment {public static final String TAG=RightFragment;@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {// TODO Auto-generated method stubLog.d(TAG, onCreateView);View view=inflater.inflate(R.layout.right_fragment,container, false);return view;}@Overridepublic void onActivityCreated(Bundle savedInstanceState) {// TODO Auto-generated method stubsuper.onActivityCreated(savedInstanceState);Log.d(TAG, onActivityCreated);}@Overridepublic void onAttach(Activity activity) {// TODO Auto-generated method stubsuper.onAttach(activity);Log.d(TAG, onAttach);}@Overridepublic void onCreate(Bundle savedInstanceState) {// TODO Auto-generated method stubsuper.onCreate(savedInstanceState);Log.d(TAG, onCreate);}@Overridepublic void onDestroy() {// TODO Auto-generated method stubsuper.onDestroy();Log.d(TAG, onDestroy);}@Overridepublic void onDestroyView() {// TODO Auto-generated method stubsuper.onDestroyView();Log.d(TAG, onDestroyView);}@Overridepublic void onDetach() {// TODO Auto-generated method stubsuper.onDetach();Log.d(TAG, onDetach());}@Overridepublic void onPause() {// TODO Auto-generated method stubsuper.onPause();Log.d(TAG, onPause);}@Overridepublic void onResume() {// TODO Auto-generated method stubsuper.onResume();Log.d(TAG, onResume);}@Overridepublic void onStart() {// TODO Auto-generated method stubsuper.onStart();Log.d(TAG, onStart);}@Overridepublic void onStop() {// TODO Auto-generated method stubsuper.onStop();Log.d(TAG, onStop);}}
Print the log in the callback method and run the program. When the RightFragment is loaded to the screen for the first time, call the method as follows:
When the first object is loaded, the onAttach, onCreate, onCreateView, onActivityCreated, onStart, and onResume methods are called in sequence.
Click the button on the left to output the following logs:
As AnotherRightFragment replaces RightFragment, The RightFragment enters the stop state, so the onPause, onStop, and onDestroyView methods will be executed. Of course, if the addToBackStack method is not called during the replacement, the RightFragment will enter the destroy state, and the onDestroy and onDetach methods will be executed.
Press the Back key and the RightFragment will overwrite it Back to the screen and print the following information:
The onActivityCreated, onStart, and onResume methods are executed because the RightFragment method returns to the running status. Note that the onCreate and onCreateView methods will not be executed at this time, because we have used the addToBackStack method to make the RightFragment and its views not destroyed. In this case, press the back key to exit the program and print the following information:
The onPause, onStop, onDestroyView, onDestroy, and onDetach methods are executed in sequence.
In addition, you can use the onSaveInstanceState method to save data in fragments. The reason is that fragments in the stopped state may be recycled when the system memory is insufficient. The stored data is rewritten in the onCreat, onCreateView, and onActivityCreate methods. They all contain a Bundle type parameter.
Dynamic Layout loading skills
Dynamic Layout loading is powerful and can solve many problems in practice. However, it only adds and replaces some operations in a layout file. If the program can decide which layout to load based on the device resolution or screen size, we can play more space.
1. Use a qualifier
Modify the activity_main.xml file in the FragmentTest project. The Code is as follows:
Here, we will delete all the unnecessary code, leave the value with a left-side fragment, and fill it with the entire parent layout. Next, create the layout-large folder in the res directory and create a layout under the folder, also known as activity_main.xml. The Code is as follows:
The layout/activity_main.xml layout contains only one part, that is, the single page mode. The layout-large/activity_main.xml layout contains two parts, that is, the double page mode. Large is a qualifier. devices that are identified as large automatically load the layout-large folder, the layout in the layout folder is also loaded for devices with small screens.
Block the event by clicking the button in MainActivity. The Code is as follows:
Package com. wj. fragmenttest; import android. app. activity; import android. app. fragmentManager; import android. app. fragmentTransaction; import android. OS. bundle; import android. view. menu; import android. view. view; import android. view. view. onClickListener; import android. widget. button; public class MainActivity extends Activity implements OnClickListener {@ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); Button button = (Button) findViewById (R. id. button1); button. setOnClickListener (this) ;}@ Overridepublic boolean onCreateOptionsMenu (Menu menu) {// Inflate the menu; this adds items to the action bar if it is present. getMenuInflater (). inflate (R. menu. main, menu); return true ;}@ Overridepublic void onClick (View v) {// TODO Auto-generated method stub/* switch (v. getId () {case R. id. button1: // create fragments AnotherRightFragment fragment = new shards (); // Get layout manager FragmentManager fragmentManager = getFragmentManager (); // get FragmentTransaction transaction = fragmentManager. beginTransaction (); // replace id with R. id. transaction in right_layout. replace (R. id. right_layout, fragment); transaction. addToBackStack (null); transaction. commit (); // submit the transaction break; default: break ;}*/}}
The following figure shows how to run a program on a flat simulator:
Start a mobile phone simulator and run the program on the simulator. The effect is as follows:
In this way, the layout is dynamically loaded.
Common delimiters in android
Size:
Small resources provided to small screen devices
Resources provided by normal to medium screen devices
Resources provided by large to large screen devices
Resources provided by xlarge to ultra-large screen devices
Resolution:
Ldpi information provided to low-resolution devices (below 120dpi)
Resources provided by mdpi to medium-resolution devices (120dpi to 160 dpi)
Resources provided by hdpi to high-resolution devices (240 dpi to dpi)
Resources provided by xhdpi to high-resolution devices (320 dpi to dpi)
Direction:
Resources provided by land to horizontal screen devices
Resources provided by port to portrait Devices
2. Use the minimum width qualifier
The minimum width qualifier allows us to specify a minimum value (in dp) for the screen width, and then take this minimum value as the critical point. The layout is loaded for devices whose screen width is greater than this value, if the screen width is smaller than this value, the device loads another layout.
Create a new layout-sw600dp folder under the res directory, and then create a new activity_main.xml layout under this folder, the Code is as follows:
When the program runs on a device with a screen width greater than 600dp, it loads the layout-sw600dp/activity_main.xml layout, when the program runs on a device with a screen width less than 600dp, the default layout/activity_main.xml layout is still loaded.
Note: The minimum width qualifier is introduced in android3.2. Because it seems to be compatible with System Version 4.0, you can use it with confidence.
Reprinted Please note: http://blog.csdn.net/j903829182/article/details/40707273