<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"> <!-- 或 vertical -->
<fragment
android:id="@+id/frag_left"
android:name="com.example.LeftFragment" <!-- 必須指定完整類名 -->
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1" />
<fragment
android:id="@+id/frag_right"
android:name="com.example.RightFragment"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1" />
</LinearLayout>
| 現象 | 可能原因 | 解決 |
|---|---|---|
| InflateException: Binary XML file line #X: Error inflating class fragment | 類名拼錯 / 類未繼承 Fragment / 包名錯誤 | 檢查 `android:name` 與 Java 類完全一致 |
| IllegalArgumentException: No view found for id 0x... for fragment... | Fragment 類中 `onCreateView` 返回 null / 佈局文件不存在 | 確保 `onCreateView` inflate 正確佈局並返回 View |
| 運行時崩潰,提示 duplicate id | 兩個 fragment 缺少 id 或 id 相同 | 為每個 fragment 指定唯一 android:id |
| Fragment 之間無法通信 | 直接持有引用調用 | 通過 Activity 做中介:`((MainActivity)getActivity()).onFragmentMessage(...)` |
public class LeftFragment extends Fragment {
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_left, container, false);
}
}
**靜態 XML 加載 Fragment 最省事**,只要類名對、id 唯一、佈局對,基本不會報錯。動態添加 (`FragmentTransaction`) 適用於運行時條件判斷、標籤頁切換等場景。