View fragmentView = getSupportFragmentManager()
.findFragmentById(R.id.fragment_container)
.getView(); // 可能返回 null
if (fragmentView != null) {
TextView tv = fragmentView.findViewById(R.id.text_view);
// 操作 tv
}
getSupportFragmentManager() (AndroidX) 或 getFragmentManager() (舊版)。findFragmentById(R.id.your_fragment_id) 或 findFragmentByTag("tag")。fragment.getView() — 注意:Fragment 必須已附加且 onCreateView 執行完畢,否則返回 null。fragmentView.findViewById(R.id.target_view)。| 問題 | 原因 | 解決 |
|---|---|---|
| getView() 返回 null | Fragment 未附加、onCreateView 未執行、視圖已銷毀 | 在 onResume/onStart 後操作,或用接口回調通知 Activity |
| ClassCastException | findFragmentById 返回的 Fragment 類型不匹配 | 轉型前用 instanceof 檢查,或用泛型 findFragmentById |
| 跨 Fragment 通信 | 直接持有引用導致耦合、內存洩漏 | 定義接口回調,或用 ViewModel/EventBus 解耦 |
// Fragment 定義接口
public interface OnDataListener {
void onDataReady(String data);
}
// Activity 實現接口
public class MainActivity extends AppCompatActivity implements MyFragment.OnDataListener {
@Override
public void onDataReady(String data) {
// 安全更新 UI
}
}
// Fragment 中調用
((OnDataListener) getActivity()).onDataReady("data");
直接通過 findFragmentById().getView().findViewById() 可行但脆弱,**推薦使用接口/ViewModel 實現雙向通信**,符合架構分層原則。