3月 25, 2020 Android
在使用 Fragment Transaction 時,我們可以為 Fragment 傳入一些參數,來改變 Fragment 的起始設定。

### 使用 Bundle

在 Android 中,Bundle 就像一個 JSONObject 物件,可以使用 Key-Value 的方式來放入 / 取出一些常用的資料型別。我們可以通過 Bundle 來把資料傳入到 Fragment 內。

### 例子

以下代碼會建立一個 Bundle Object,然後設定 id 及 name 值,再把 Bundle Object 傳入到 MyFragment 內 :

```java
// create bundle object
Bundle bundle = new Bundle();

bundle.putInt("id", 1);

bundle.putString("name", "19Site");

// create fragment object
Fragment fragment = new MyFragment();

// set bundle as fragment arguments
fragment.setArguments(bundle);

// prepare fragment transaction
FragmentTransaction mFragmentTransaction = getSupportFragmentManager().beginTransaction();

mFragmentTransaction.addToBackStack(null);

mFragmentTransaction.replace(R.id.frame_layout, fragment);

mFragmentTransaction.commit();
```

在檔案 `MyFragment.java` 內,我們可以使用 `getArguments()` 來取得傳入的 Bundle Object :

```java
// get arguments
Bundle bundle = getArguments();

// get values from bundle
int id = bundle.getInt("id", 0);

String name = bundle.getString("name", null);
```
過去文章
2025 (9)
4 (5)
3 (1)
2 (3)
2024 (25)
11 (3)
10 (3)
9 (1)
3 (18)
2022 (6)
10 (1)
6 (2)
5 (1)
3 (1)
1 (1)
2021 (21)
11 (7)
7 (1)
6 (2)
5 (2)
4 (6)
3 (2)
2 (1)
2020 (92)
12 (1)
11 (2)
10 (4)
9 (10)
8 (5)
7 (1)
6 (3)
5 (1)
4 (4)
3 (25)
2 (7)
1 (29)
2019 (57)
12 (25)
11 (7)
9 (25)