android:appComponentFactory,Android onSaveInstanceState onRestoreInstanceState

 2023-11-19 阅读 18 评论 0

摘要:In this tutorial, we’ll be discussing the two vital methods for managing the state of the application, namely onSaveInstanceState and onRestoreInstanceState. We’ll be developing a Counter Android Application in which we’ll handle the state of the appli

In this tutorial, we’ll be discussing the two vital methods for managing the state of the application, namely onSaveInstanceState and onRestoreInstanceState.
We’ll be developing a Counter Android Application in which we’ll handle the state of the application when the configuration changes.

在本教程中,我們將討論管理應用程序狀態的兩個重要方法,即onSaveInstanceStateonRestoreInstanceState
我們將開發一個Counter Android應用程序,當配置更改時,我們將在其中處理應用程序的狀態。

Android生命周期 (Android Lifecycle)

Following is the lifecycle of the Activities in our application:

android:appComponentFactory、 以下是我們應用程序中活動的生命周期:

Whenever there is a configuration change, such as rotation or application going into multi-window mode, the activity is recreated.

每當進行配置更改(例如輪換或應用程序進入多窗口模式)時,都會重新創建活動。

In this recreation, the application gets restarted and may lose data in the views if not handled properly.

android.intent.category.DEFAULT, 在這種娛樂中,應用程序將重新啟動,并且如果處理不當,可能會丟失視圖中的數據。

For this there are two methods that are triggered at different stages of the lifecycle:

為此,有兩種方法在生命周期的不同階段觸發:

  • onSaveInstanceState

    onSaveInstanceState
  • onRestoreInstanceState

    onRestoreInstanceState

They are used to save and retrieve values. The values are stored in the form of a key-value pair.
Let’s look at each of them separately.

Linux on Android。 它們用于保存和檢索值。 這些值以鍵值對的形式存儲。
讓我們分別看一下它們。

onSaveInstanceState (onSaveInstanceState)

onSaveInstanceState method gets called typically before/after onStop() is called. This varies from Android version to version. In the older versions it used to get before onStop().

通常在調用onStop()之前/之后調用onSaveInstanceState方法。 視Android版本而異。 在舊版本中,它通常先于onStop()獲得。

Inside this method, we save the important values in the Bundle in the form of key value pairs.

basedonandroid手機, 在此方法內部,我們以鍵值對的形式將重要值保存在Bundle中。

The onSaveInstanceState method looks like :

onSaveInstanceState方法如下所示:

@Overridepublic void onSaveInstanceState(Bundle outState) {super.onSaveInstanceState(outState);}

On the outState bundle instance we add the key value pairs. Following are the methods applicable:

在outState捆綁實例上,我們添加鍵值對。 以下是適用的方法:

We can pass custom class instances by setting the class as Parcelable or Serializable.

我們可以通過將類設置為Parcelable或Serializable來傳遞自定義類實例。

Let’s look at an example using Parcelable since it is faster than Serializable.

讓我們看一個使用Parcelable的示例,因為它比Serializable更快。

Following is a custom class :

以下是一個自定義類:

public class Model implements Parcelable {public long id;public String name;public Model(long id, String name) {this.id = id;this.name = name;}protected Model(Parcel in) {id = in.readLong();name = in.readString();}public final Creator<Model> CREATOR = new Creator() {@Overridepublic Model createFromParcel(Parcel in) {return new Model(in);}@Overridepublic Model[] newArray(int size) {return new Model[size];}};@Overridepublic int describeContents() {return 0;}@Overridepublic void writeToParcel(Parcel parcel, int i) {parcel.writeLong(id);parcel.writeString(name);}}

writeToParcel method is where we set the class properties on the Parcelable instance.

writeToParcel方法是我們在writeToParcel實例上設置類屬性的地方。

Now create an instance of the Model and save it in onSaveInstanceState.

現在創建Model的實例并將其保存在onSaveInstanceState

Model model = new Model(10, "Hello");@Overridepublic void onSaveInstanceState(Bundle outState) {super.onSaveInstanceState(outState);outState.putParcelable("parcelable", model);}

Now we can retrieve these saved values in the onRestoreInstanceState method.

現在,我們可以在onRestoreInstanceState方法中檢索這些保存的值。

Note: onSaveInstanceState gets called whenever you press the home button in your application as well.注意 :每當您在應用程序中按下主頁按鈕時,也會調用onSaveInstanceState。

Another note: Things like EditText can save and restore their content implicitly provided you’ve set an id on the View. Activity will automatically collect View’s State from every single View in the View hierarchy.

另一個注意事項 :只要您在View上設置了id,諸如EditText之類的內容就可以隱式保存和恢復其內容。 活動將從視圖層次結構中的每個單個視圖自動收集視圖狀態。

onRestoreInstanceState (onRestoreInstanceState)

This method gets triggered only when something was saved in onSaveInstanceState method.
It gets called after onStart().

僅當在onSaveInstanceState方法中保存了某些內容時,才會觸發此方法。
它在onStart()之后被調用。

@Overrideprotected void onRestoreInstanceState(Bundle savedInstanceState) {super.onRestoreInstanceState(savedInstanceState);Model model = savedInstanceState.getParcelable("parcelable");}

Following are the other method available:

以下是可用的其他方法:

The super method implementation restores the view hierarchy.
超級方法實現可還原視圖層次結構。

Generally, onRestoreInstanceState isn’t used to restore values often now. The same can be done from the Bundle in the onCreate method. Also since the onCreate method is always called before, it is a good practice to restore the saved instances there only.

通常, onRestoreInstanceState現在不經常用于還原值。 可以通過onCreate方法中的Bundle完成相同的操作。 另外,由于始終在之前調用onCreate方法,因此,僅在此處還原保存的實例是一種好習慣。

In the following section, we’ll be creating a Counter Application in which we’ll save the state of the counter using the above methods.

在下一節中,我們將創建一個計數器應用程序,在其中使用上述方法保存計數器的狀態。

項目結構 (Project Structure)

(Code)

The code for the activity_main.xml is given below:

下面給出了activity_main.xml的代碼:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"xmlns:tools="https://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"android:layout_margin="16dp"android:orientation="vertical"tools:context=".MainActivity"><EditTextandroid:id="@+id/inName"android:layout_width="match_parent"android:layout_height="wrap_content"android:hint="Username" /><EditTextandroid:layout_width="match_parent"android:layout_height="wrap_content"android:hint="Phone number"android:inputType="phone" /><TextViewandroid:id="@+id/textView"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="0"android:textSize="32sp" /><Buttonandroid:id="@+id/button"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="COUNT UP" /></LinearLayout>

In the above layout, the second EditText doesn’t have any id set. So when the device is rotated or any configuration happens that causes the activity to recreate, this EditText contents would be reset.

在上面的布局中,第二個EditText沒有設置任何ID。 因此,當設備旋轉或發生任何導致活動重新創建的配置時,此EditText內容將被重置。

The code for the MainActivity.java is given below:

MainActivity.java的代碼如下:

package com.journaldev.androidsaverestoreinstance;import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;public class MainActivity extends AppCompatActivity {Button button;TextView textView;int counter;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);if (savedInstanceState != null) {String message = savedInstanceState.getString("message");Toast.makeText(this, message, Toast.LENGTH_LONG).show();counter = savedInstanceState.getInt("counter", 0);}button = findViewById(R.id.button);textView = findViewById(R.id.textView);textView.setText(String.valueOf(counter));button.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {counter = Integer.valueOf(textView.getText().toString()) + 1;textView.setText(String.valueOf(counter));}});}@Overridepublic void onSaveInstanceState(Bundle outState) {super.onSaveInstanceState(outState);outState.putString("message", "This is a saved message");outState.putInt("counter", counter);}@Overrideprotected void onRestoreInstanceState(Bundle savedInstanceState) {super.onRestoreInstanceState(savedInstanceState);Toast.makeText(getApplicationContext(), "onRestoreInstanceState", Toast.LENGTH_SHORT).show();counter = savedInstanceState.getInt("counter", 0);}}

In this the save the integer value of the counter and then when the activity is recreated, the onCreate gets called again. Over there we check if the savedInstanceState Bundle is null or not. If it isn’t we restore the views with the data from the counter.

在這種情況下,保存計數器的整數值,然后在重新創建活動時,再次調用onCreate。 在那兒,我們檢查saveInstanceStateState Bundle是否為null。 如果不是,我們將使用計數器中的數據還原視圖。

The output of the application in action is given below:

實際應用程序的輸出如下:

Notice that the Phone Number field goes empty when the orientation was changed.

請注意,更改方向后,“電話號碼”字段為空。

This brings an end to this tutorial. You can download the project from the link below.

本教程到此結束。 您可以從下面的鏈接下載項目。

AndroidSaveRestoreInstanceAndroidSaveRestoreInstance
Github Project LinkGithub項目鏈接

翻譯自: https://www.journaldev.com/22621/android-onsaveinstancestate-onrestoreinstancestate

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/1/183114.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息