Activity 透過 Intent 傳值給另一個 Activity,該 Activity 再將資料塞給內部 Fragment。若直接在 Fragment 呼叫 getArguments() 卻拿到 null,通常是因為未正確建立並設定 Bundle 給 Fragment。
// Activity1
Intent intent = new Intent(this, Activity2.class);
intent.putExtra("key_user_id", 12345);
intent.putExtra("key_token", "abcde");
startActivity(intent);
// Activity2.onCreate()
Bundle bundle = new Bundle();
bundle.putInt("user_id", getIntent().getIntExtra("key_user_id", -1));
bundle.putString("token", getIntent().getStringExtra("key_token"));
// 關鍵:建立 Fragment 實例並 setArguments
MyFragment fragment = new MyFragment();
fragment.setArguments(bundle);
// 加入 ViewPager 或 FragmentTransaction
getSupportFragmentManager().beginTransaction()
.replace(R.id.container, fragment)
.commit();
// MyFragment
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// getArguments() 此時已非 null
Bundle args = getArguments();
if (args != null) {
int userId = args.getInt("user_id", -1);
String token = args.getString("token", "");
// 後續邏輯...
}
}
| 錯誤寫法 | 後果 | 修正方式 |
|---|---|---|
在 Fragment 建構子呼叫 setArguments() | Fragment 可能被系統重建導致參數遺失 | 務必在 onCreate() 前由宿主 Activity 設定 |
直接 new MyFragment() 後未 setArguments | getArguments() 回傳 null | 建立實例後立即呼叫 setArguments(bundle) |
使用 putExtra 直接塞給 Fragment | Fragment 無法直接讀取 Activity Intent | 必須轉為 Bundle 經由 setArguments |
public class MyPagerAdapter extends FragmentPagerAdapter {
private final Bundle args;
public MyPagerAdapter(FragmentManager fm, Bundle args) {
super(fm);
this.args = args;
}
@Override
public Fragment getItem(int position) {
MyFragment f = new MyFragment();
f.setArguments(args); // 每個分頁共用同一份參數
return f;
}
// ...
}
最佳實務: 定義 newInstance(Bundle args) 靜態工廠方法封裝建立邏輯,避免散落在各處。