能用靜態 XML 佈局就不用動態代碼創建 View。XML 佈局可視化、易維護、支持預覽、編譯時優化,動態代碼僅用於極少數運行時才能確定的場景。
public class MyFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// 正確:使用 getActivity() 或 requireContext()
LinearLayout layout = new LinearLayout(requireContext()); // API 23+ 推薦
// 或
LinearLayout layout = new LinearLayout(getActivity()); // 兼容舊版
layout.setOrientation(LinearLayout.VERTICAL);
layout.setLayoutParams(new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT
));
// 添加子 View
TextView tv = new TextView(requireContext());
tv.setText("動態添加");
layout.addView(tv);
return layout; // 或加入到父容器
}
}
// LayoutParams 必須匹配父容器類型
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT
);
lp.setMargins(16, 16, 16, 0); // 左上右下
lp.weight = 1f; // 權重
childView.setLayoutParams(lp);
| 錯誤 | 後果 | 修正 |
|---|---|---|
| 用 getApplicationContext() 創建 View | 主題屬性異常、Dialog 彈出崩潰 | 用 getActivity()/requireContext() |
| LayoutParams 類型不匹配父容器 | ClassCastException 或佈局失效 | 父容器是 LinearLayout 就用 LinearLayout.LayoutParams |
| 未設置 LayoutParams 直接 addView | 默認 WRAP_CONTENT×WRAP_CONTENT,可能不顯示 | 顯式設置 LayoutParams |
// 1. XML 定義 item_template.xml
// 2. 代碼中膨脹並修改
View item = LayoutInflater.from(context).inflate(R.layout.item_template, parent, false);
TextView tv = item.findViewById(R.id.tv_title);
tv.setText(dynamicTitle);
container.addView(item);
堅持「XML 為主、代碼為輔」,Fragment 用 requireContext() 獲取上下文,動態佈局必須匹配父容器 LayoutParams 類型,是 Android UI 開發的工程化原則。