首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Android Activity 調用 Fragment 公共方法報 NullPointerException:生命周期未同步

     編輯:程式設計綜合問答

問題代碼

// 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 尚未初始化。

標準解法:使用 Arguments 傳遞數據

// 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 生命周期,又避免了空指針風險。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved