Android basic notes (18)-Fragment, androidfragment

Source: Internet
Author: User

Android basic notes (18)-Fragment, androidfragment

  • Blog sentiment end-start
  • What is Fragment?
  • Add fragment to Activity in two ways
  • Fragment Lifecycle
  • Fragment backward compatibility
  • Communication between Fragment

Blog sentiment, end point-start

This is the last blog on the foundation. I learned a lot and felt a lot.

Here is a general summary.

Persistence is often difficult, and it is more difficult to stick to perfection. This is the sentiment of writing these 18 blogs.

Time is quickly lost, and I always feel that time is not enough. This will gradually reduce the quality of your blog. Today I reflected on it. Aren't I making a "Broken window? (If you do not know the broken window theory, you can check it out)

I wrote 18th articles, and I felt a lot confused. I think there is still a very bad difference between the "knowledge point" and the "knowledge point" described in the organizational language.

This is the last basic blog, that is, the end and the start. The end is your unbelieving attitude, and the end is a brand new Android journey.

There is no end to learning and no end to technology. From today on, we will urge ourselves to be earnest, earnest, and earnest.

The opportunity may be met by you, but you will not be able to seize it if you have not worked hard before.

What is Fragment?

Fragment was introduced in Android3.0. It is mainly used on large screen devices and supports dynamic and more flexible uidesign (such as flat panel ).

Fragment is an action or part of the UI in an Activity. You can think of fragment as a modular area of an activity. It has its own lifecycle and receives its own input events, it can also be added or deleted during the activity running (a bit like a "sub-activity" that can be reused in different activities ").

Fragment must be embedded in an activity. Their lifecycles are directly affected by the lifecycles of their host activity. When an activity is running, you can operate on each Fragment independently, such as adding or deleting them.

Fragment can define its own layout and lifecycle callback methods. Therefore, fragment can be reused in multiple activities. Therefore, fragment combinations can be changed based on different screen sizes or usage scenarios.

Add fragment to Activity in two ways
Method 1: insert <fragmetn>As a child element of the layout, follow these steps:

① Add in layout File<fragment>Label, and specifyandroid:nameProperty is an inheritanceFragment.

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="horizontal" >    <fragment        android:id="@+id/list"        android:name="com.bzh.layout.Fragment1"        android:layout_width="0dp"        android:layout_height="match_parent"        android:layout_weight="1" /></LinearLayout>

② Create inheritanceFragmentAnd rewriteonCreateView()Method.inflate.inflate(R.layout.fragment1,null)Generate a View object using the XML file as the root layout of fragment

public class Fragment1  extends Fragment{    @Override    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {        View view = inflater.inflate(R.layout.fragment1, null);        return view;    }}

③ Create a layout file named fragment1

<? Xml version = "1.0" encoding = "UTF-8"?> <LinearLayout xmlns: android = "http://schemas.android.com/apk/res/android" android: layout_width = "match_parent" android: layout_height = "match_parent" android: orientation = "vertical"> <TextView android: layout_width = "match_parent" android: layout_height = "match_parent" android: text = "I am Fragment1"/> </LinearLayout>

The result is as follows:

Directly in the layout File<fragment>The steps of elements are relatively simple, but we can see that they are still not flexible, and they are not used much in actual use.

In addition, each fragment requires a unique identifier. If the activity restarts, the system can restore the Fragment and capture the Fragment to process the transaction, for example, remove it. There are three methods to provide an ID for a fragment:
Use the android: id attribute to provide a unique ID;
Use the android: tag attribute to provide a unique string;
If none of the above two items are provided, the system uses the ID of the container view;
Method 2: Use encoding to add or replace fragment with an existing one. ViewGroupLayout.
In the same way as the first method, we still need to prepare an inheritance FragmentClass, and prepare a layout file for it. onCreateView()In the callback, use the filler to return its instance as the layout.

The difference is that we need to useFragmentManagerClass, and start the transaction, of course, the transaction must be committed at the end.

WindowManager wm = (WindowManager) getSystemService (WINDOW_SERVICE); int height = wm. getdefadisplay display (). getHeight (); int width = wm. getdefadisplay display (). getWidth (); // get the Fragment manager FragmentManager = getFragmentManager (); // start the transaction FragmentTransaction fragmentTransaction = fragmentManager. beginTransaction (); if (height> width) {// use Fragment to replace the specified layout fragmentTransaction. replace (android. r. id. content, new Fragment1 ();} else {// use Fragment to replace the specified layout fragmentTransaction. replace (android. r. id. content, new Fragment2 ();} // submit the transaction fragmentTransaction. commit ();
Fragment Lifecycle
The lifecycle of Fragment is similar to that of activity.
OnAttach: bind to activity
OnCreate: Create fragment
OnCreateView: Create a fragment Layout
OnActivityCreated: after the activity is created
OnStart: visible, not interactive
OnResume: visible and interactive
OnPause: Partially visible and interactive
OnStop: invisible
OnDestroyView: destroys the view object of fragment.
OnDestroy: fragment destroyed
OnDetach: unbound from activity
In actual development, of course, not all will be overwritten. Google recommends that we rewrite at least three methods:
OnCreate () can initialize some components when the fragment is created.
OnCreateView () when drawing the fragmetn interface for the first time, we must return a View object as the root layout of fragmetn.
OnPause () When fragment cannot interact with users.
Fragment backward compatibility
Fragment is only available in Android 3.0. To use Fragment in earlier versions of Android 3.0, perform the following two steps:
Change all Fragment and FragmentManager to classes under the support-v4 package
Change the inheritance of Activity to FragmentActivity (under the support-v4 package)
Communication between Fragment

The communication between two Fragment mainly relies onFragmentObject To set a Tag and useFragmentManager.findFragmentByTag()Method, find the TagFragmentObjects to achieve the purpose of communication.

The following is a small case. In the main layout, there are twoLinearLayoutLayout.Fragment1AndFragment2Fill. WhereFragment1ContainsButton, Can be modifiedFragment2OfTextViewContent.

First, replace two Fragment entries in MainActivity with the specified layout.

LinearLayout ll1 = (LinearLayout) findViewById (R. id. ll1); LinearLayout ll2 = (LinearLayout) findViewById (R. id. ll2); FragmentManager fm = getFragmentManager (); FragmentTransaction ft = fm. beginTransaction (); // set the tag of the Fragment1 object to fragment 1ft. replace (R. id. ll1, new Fragment1 (), "fragment1"); // set the tag to fragment 2ft for the Fragment1 object. replace (R. id. ll2, new Fragment2 (), "fragment2"); ft. commit ();

In Fragment2, We need to expose the method for modifying TextView content to the outside world, which is also very simple:

Public class Fragment2 extends Fragment {private TextView TV; @ Override public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {View view View = inflater. inflate (R. layout. fragment2, null); TV = (TextView) view. findViewById (R. id. TV); return view;} // expose the TextView Method to the outside world to public void setTextView (String content) {TV. setText (content );}}

The next thing is very simple. In Fragment1, find the Fragment2 object based on the Tag, and then modify it.

Public class Fragment1 extends Fragment {@ Override public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {View view View = inflater. inflate (R. layout. fragment1, null); Button btn = (Button) view. findViewById (R. id. btn); btn. setOnClickListener (new OnClickListener () {@ Override public void onClick (View v) {// use the Fragment manager to find the object Fragment2 f2 = (Fragment2) getFragmentManager () with tags (). findFragmentByTag ("fragment2"); f2.setTextView ("my friend") ;}}); return view ;}}

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.