// Activity 中
ForgetPSD2Fragment fragment2 = new ForgetPSD2Fragment();
transaction.replace(R.id.fragmentcontainer, fragment2);
fragment2.setViewPhone(phone); // 這裡 fragment 還未 attach,view 為 null
// Fragment 中
private TextView txtPhone;
@Override
public View onCreateView(...) {
view = inflater.inflate(...);
txtPhone = view.findViewById(R.id.txtphone);
}
public void setViewPhone(String phone) {
if (txtPhone == null) Log.i("debug", "null"); // 進入此分支
else txtPhone.setText(phone);
}
FragmentTransaction.replace() 只是將事務加入隊列,Fragment 的生命周期方法(onAttach、onCreateView)要在事務提交後才會執行。此時直接調用 setViewPhone,txtPhone 尚未初始化。
// Activity
Bundle bundle = new Bundle();
bundle.putString("phone", phone);
fragment2.setArguments(bundle);
transaction.replace(R.id.fragmentcontainer, fragment2);
transaction.commit();
// Fragment
@Override
public void onCreateView(...) {
String phone = getArguments().getString("phone");
txtPhone = view.findViewById(R.id.txtphone);
txtPhone.setText(phone); // view 已創建,安全賦值
}
這樣既符合 Fragment 生命周期,又避免了空指針風險。