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

Android 動態佈局最佳實踐:優先靜態 XML,Fragment 中 Context 獲取

     編輯:程式設計疑難解答

核心建議

能用靜態 XML 佈局就不用動態代碼創建 View。XML 佈局可視化、易維護、支持預覽、編譯時優化,動態代碼僅用於極少數運行時才能確定的場景。

何時必須用動態佈局

  • 列表項類型超過 10 種且高度動態(RecyclerView 多類型已解決)。
  • 根據後端配置動態生成表單欄位。
  • 插件化/熱更新模塊,佈局不隨 APK 打包。

Fragment 中動態創建 View 正確 Context


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

混合模式:XML 定義模板 + 代碼克隆


// 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 開發的工程化原則。

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