Android 5-day Activity jump and data transmission, Fragment, androidfragment

Source: Internet
Author: User

Android 5-day Activity jump and data transmission, Fragment, androidfragment
1 Activity Lifecycle

Activity has three statuses: running, paused, and stopped in the life cycle. Each time a status change occurs, an Activity method notifies the activity of the status change message. Shows the lifecycle, status, and method called by the system during status switching of an activity.

2. Three scenarios of Activity status change

There are many scenarios for changing the Activity status. Here are three typical scenarios: press the back key, press the home key, and flip the screen.

First, open the application. By setting the log information for each method of the activity, you can see that the activity object calls onCreate (start) at a time)OnStart (visible)OnResume (to the foreground) three methods.
(1) press the rollback key.

As you can see, the activity calls onPause in sequence (exit the foreground)OnStop (invisible)OnDestroy (destroy) three methods, activity lifecycle ends.
(2) press the home Key.

First, let's take a look at the log information:

As you can see, after the onResume (to the front-end) method, we press the home Key and call the onPause (to exit the front-end) method. Let's talk about the onSaveInstanceState method later. Next we will use the onStop (invisible) method. The above is the call process after pressing the home key. You can find that *, activity does not have destroy! * As a user of android phones, we all know that this is of course. When we click this application again from the task manager, the application will come to the foreground, and the Web pages and games we open will be the same as before pressing the home key. As shown in the log information, the onCreate method is not called after the application is selected again, but the onstart (visible)-> onResume (foreground) method is used directly ).

(3) rotating the screen

Device rotation is a very common operation. You can use ctrl + F12 when using avd.

It is worth noting that when the device rotates, the current activity will be destroyed and a new activity will be created!


This destruction-reconstruction brings two problems:

1. When the screen is converted to a horizontal or vertical screen, the displayed activity layout may show unexpected results. For example, if a layout file is created in portrait mode, the control may be misplaced when the horizontal screen is displayed.

2. After the activity is rebuilt, the data of the previous operation will be lost. Imagine that if the browser you use does not take device rotation into consideration, but you read the novel well and accidentally turn it down. After the screen turns around, the browser will return to the homepage.

The solution to the first problem is relatively simple: Configure one more layout for the horizontal screen.


Create the layout-land folder. Note that the new layout file must have the same file name as the previous layout file. The layout file written in layout-land is displayed on the horizontal screen.

For the second problem, we need to reference the Big Boss: Bundle in android development. You can think of Bundle as a structure to save the "key-value" pair, and it is responsible for transmitting values in each activity.

In this scenario, what we need to do is to pass the value we need to retain to the Bundle object before the current activity is destroyed (if you are reading a novel, you need to pass the current page information you browsed to Bundle ). When the new activity oncreate,

Check whether the Bundle object (as a parameter of the onCreate method) has required information. If so, the Bundle object is retrieved and rendered.

The method for saving data to Bundle is onSaveInstanceState. Previously, it was called after the onPause method was called.

@Override    public void onSaveInstanceState(Bundle savedInstanceState){        super.onSaveInstanceState(savedInstanceState);        Log.i(TAG, "onSaveInstanceState");        savedInstanceState.putString("friend",mFriend);    }

Then, when the onCreate method uses the friend object, it is taken directly from the Bundle:


 
The above process is shown in:

3 jump between activities

First, you need to create a second activity.

You can create an activity in three steps:

1) Create an activity file

2) create a layout file for the activity.

3) configure a new activity in AndroidManifest.

There is nothing to say about the first two steps. Just like the class file and layout file automatically generated when you create a project, you can configure the activity in AndroidManifest as follows:


You can use the startActivity method to redirect between activities:

Intent i =new Intent(MainActivity.this,MainActivity2.class);              startActivity(i);

Intent is the medium for communication between component and the operating system.Operating SystemSend a request so that ActivityManager can locate the activity to be started through the Intent content. Therefore, the activity to be started must be declared in androidmanifest first.

4. data transmission between activities

There are two types of data transmission between activities: Jump and rollback.

When a jump occurs, you can actually put the data you want to transmit into the Intent object.

Intent i =new Intent(MainActivity.this,MainActivity2.class);i.putExtra("num",num);startActivity(i);

The Extra for saving data in Intent is actually similar to the Bundle mentioned earlier, and it is also a key-value structure.

If you want to use the transmitted data in MainActivity2, use getIntent:

num=getIntent().getIntExtra("num",0);

The second scenario where data transmission occurs is to return to the previous activity through the "back-to-back" button.

In this case, because the last page does not return to the previous page by jump, data cannot be placed in the Intent.

When we need the response results of the subpage, use the startActivityForResult method instead of the startActivity method:

Intent i =new Intent(MainActivity.this,MainActivity2.class);i.putExtra("num",num);startActivityForResult(i,0);

On the subpage, you must use the setResult method.

Intent i =new Intent();        i.putExtra("num", num);        setResult(RESULT_OK, i);

In this way, you only need to override the onActivityResult method in the parent activity:

protected void onActivityResult(int requestCode,int resultCode,Intent data){        if(data==null){            return;        }        num=data.getIntExtra("num",0);    }

The interaction process is as follows:

5 UI Fragment and Fragment Manager

Fragment is a controller object that can be delegated by an activity to complete some tasks.

The lifecycle of fragment is similar to the lifecycle of an activity. Many Methods correspond to the lifecycle of an activity.

Three steps to create a fragment atmosphere:

1) define the Layout

2) create a Fragment class

3) Add the UI Fragment to the Fragment Manager.

In 1), it is equivalent to creating a common layout file:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:orientation="vertical" android:layout_width="match_parent"    android:layout_height="match_parent"><EditText    android:id="@+id/crime_title"    android:layout_width="match_parent"    android:layout_height="wrap_content"    android:hint="@string/crime_title_hint"/></LinearLayout>

The key is that the new Fragment class must cover two methods:

@Override    public void onCreate(Bundle savedInstanceState){        super.onCreate(savedInstanceState);        mCrime=new Crime();    }    @Override    public View onCreateView(LayoutInflater inflater,ViewGroup parent,Bundle savedInstanceState){        View v =inflater.inflate(R.layout.fragment_crime,parent,false);        mTitleField=(EditText)v.findViewById(R.id.crime_title);        mTitleField.addTextChangedListener(new TextWatcher() {            @Override            public void beforeTextChanged(CharSequence c, int start, int count, int after) {            }            @Override            public void onTextChanged(CharSequence c, int start, int before, int count) {                mCrime.setTitle(c.toString());            }            @Override            public void afterTextChanged(Editable s) {            }        });        return v;    }

You can see that creating a view is completed in the onCreateView method.

3) execute the fragment transaction through fragmentManager:

android.support.v4.app.FragmentManager fm=getSupportFragmentManager();        Fragment fragment=fm.findFragmentById(R.id.fragmentContainer);        if(fragment==null){            fragment=new CrimeFragment();            fm.beginTransaction()                    .add(R.id.fragmentContainer,fragment)                    .commit();

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.