如果 Android Fragment 存在,如何從 BackStack 中恢復它?
介紹
Android 應用程式是使用不同的元件構建的,例如 Activity 和 Fragment。Fragment 是 Activity 的輕量級版本,因此在大多數情況下用於顯示應用程式的 UI。Fragment 被認為是 Android 應用程式的重要元件之一。它們通常用於建立複雜、動態的使用者介面,這些介面既健壯又高度可定製。在 Android 應用程式中管理 Fragment 有點棘手,尤其是在從 Back Stack 中恢復 Fragment 時。在本文中,我們將瞭解如果 Android Fragment 存在,如何從 BackStack 中恢復它。
實現
我們將建立一個簡單的專案,在其中我們將顯示第一個 Fragment,在其中我們將顯示一個 TextView 和一個按鈕。我們將在這個 Activity 中顯示第一個 Fragment。點選按鈕,我們將開啟第二個 Fragment 並顯示一個 TextView。
步驟 1:在 Android Studio 中建立一個新專案
導航到 Android Studio,如下面的螢幕截圖所示。在下面的螢幕截圖中,單擊“新建專案”以建立新的 Android Studio 專案。
單擊“新建專案”後,您將看到下面的螢幕。
在此螢幕中,我們只需選擇“空活動”並單擊“下一步”。單擊“下一步”後,您將看到下面的螢幕。
在此螢幕中,我們只需指定專案名稱。然後包名稱將自動生成。
注意 - 確保選擇 Java 作為語言。
指定所有詳細資訊後,單擊“完成”以建立新的 Android Studio 專案。
建立專案後,我們將看到兩個開啟的檔案,即 activity_main.xml 和 MainActivity.java 檔案。
步驟 3:使用 activity_main.xml
導航到 activity_main.xml。如果此檔案不可見,則要開啟此檔案,在左側窗格中導航到 app>res>layout>activity_main.xml 以開啟此檔案。開啟此檔案後,將以下程式碼新增到其中。程式碼中添加了註釋以詳細瞭解。
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/idRLLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<!-- creating a frame layout for displaying a container-->
<FrameLayout
android:id="@+id/frameContainer"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
說明 - 在上面的程式碼中,我們建立了一個 RelativeLayout 作為根佈局,並在其中建立了一個 FrameLayout,我們將在其中顯示我們的第一個 Fragment,該 Fragment 將包含一個 TextView 和一個按鈕。點選按鈕,我們將開啟一個新的 Fragment。
步驟 4:建立一個新的 Fragment。
現在我們將建立一個第一個 Fragment。要建立一個新的 Fragment,請導航到 app>java>您的應用程式包名稱>右鍵單擊它>新建>Fragment 並選擇一個空的 Blank Fragment 並將其命名為 FragmentOne。建立新的 Fragment 後,將建立兩個檔案,一個是名為 FragmentOne.java 的 Java 檔案,另一個是 fragment_one.xml 檔案。類似地,我們必須建立另一個名為 FragmentTwo 的 Blank Fragment。對於此 Fragment,也將建立兩個檔案,分別命名為 fragment_two.xml 和 FragmentTwo.java 檔案。
步驟 5:使用 fragment_one.xml 檔案。
導航到 fragment_one.xml。如果此檔案不可見,則要開啟此檔案,在左側窗格中導航到 app>res>layout>fragment_one.xml 以開啟此檔案。開啟此檔案後,將以下程式碼新增到其中。程式碼中添加了註釋以詳細瞭解。
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".FragmentOne">
<!-- creating a text view for displaying tezt view on below line-->
<TextView
android:id="@+id/idTVHeading"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Welcome to First Fragment"
android:textAlignment="center"
android:textColor="@color/black"
android:textSize="20sp"
android:textStyle="bold" />
<!-- creating a button to open second fragment -->
<Button
android:id="@+id/idBtnLoadFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/idTVHeading"
android:layout_margin="20dp"
android:text="Open Second Fragment"
android:textAllCaps="false" />
</RelativeLayout>
說明 - 在上面的程式碼中,我們建立了一個 RelativeLayout 作為根佈局。在此 RelativeLayout 中,我們建立了一個 TextView 用於顯示標題,以及一個用於開啟新 Fragment 的按鈕。
步驟 6:使用 fragment_two.xml 檔案。
導航到 fragment_two.xml。如果此檔案不可見,則要開啟此檔案,在左側窗格中導航到 app>res>layout>fragment_two.xml 以開啟此檔案。開啟此檔案後,將以下程式碼新增到其中。程式碼中添加了註釋以詳細瞭解。
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".FragmentTwo">
<!-- creating a text view for displaying text view on below line-->
<TextView
android:id="@+id/idTVHeading"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Welcome to Second Fragment"
android:textAlignment="center"
android:textColor="@color/black"
android:textSize="20sp"
android:textStyle="bold" />
</RelativeLayout>
步驟 7:使用 FragmentOne.java 檔案
導航到 FragmentOne.java。如果此檔案不可見,則要開啟此檔案,在左側窗格中導航到 app>java>您的應用程式包名稱>FragmentOne.java 以開啟此檔案。開啟此檔案後,將以下程式碼新增到其中。程式碼中添加了註釋以詳細瞭解。
package com.example.androidjavaapp;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
public class FragmentOne extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_one, container, false);
// on below line creating and initializing variable for button
Button loadFragment = view.findViewById(R.id.idBtnLoadFragment);
// on below line adding click listner for our button.
loadFragment.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// on below line creating and initializing variable for fragment.
Fragment fragment = new FragmentTwo();
// on below line creating and initializing variable for fragment transcation.
FragmentTransaction transaction = getFragmentManager().beginTransaction();
// on below line replacing the container
transaction.replace(R.id.frameContainer, fragment);
// on below line adding back stack as null.
transaction.addToBackStack(null);
// on below line committing the changes.
transaction.commit();
}
});
return view;
}
}
說明 - 在上面的程式碼中,我們可以看到一個 onCreateView 方法,在此方法中,我們正在載入要顯示的佈局檔案。之後,我們正在建立和初始化按鈕的變數,並使用我們在 fragment_one.xml 檔案中提供的 id。之後,我們為該按鈕添加了一個點選監聽器。在點選監聽器方法中,我們正在開啟第二個 Fragment 並新增一個空 Back Stack,以便當使用者從第二個 Fragment 返回時,他將導航到第一個 Fragment。
步驟 7:使用 MainActivity.java 檔案
導航到 MainActivity.java。如果此檔案不可見,則要開啟此檔案,在左側窗格中導航到 app>java>您的應用程式包名稱>MainActivity.java 以開啟此檔案。開啟此檔案後,將以下程式碼新增到其中。程式碼中添加了註釋以詳細瞭解。
package com.example.androidjavaapp;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// on below line creating and initializing variable for fragment.
Fragment fragment = new FragmentOne();
// on below line creating and initializing variable for fragment transcation.
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
// on below line replacing the transaction with the fragment.
transaction.replace(R.id.frameContainer, fragment);
// on below line adding back stack as null.
transaction.addToBackStack(null);
// on below line committing changes.
transaction.commit();
}
}
說明 - 在上面的程式碼中,我們可以看到 onCreate 方法,在其中我們正在為 activity_main.xml 載入佈局。在此 onCreate 方法中,我們正在載入 FragmentOne 併為其新增 Back Stack 以及 null。
新增上述程式碼後,我們只需單擊頂部欄中的綠色圖示即可在移動裝置上執行我們的應用程式。
注意 - 確保您已連線到您的真實裝置或模擬器。
輸出
結論
在以上教程中,我們瞭解瞭如何在 Android 應用程式中建立 Fragment。我們如何在這兩個 Fragment 之間導航以及如果 Android Fragment 存在,如何從 BackStack 中恢復它。
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP