在 Android 使用 Java 程式碼動態設定 LinearLayout 背景顏色時,常見錯誤是 在 setContentView() 之前對 inflate 出來的 View 設定屬性,但隨後又呼叫 setContentView(R.layout.xxx) 覆蓋了佈局,導致設定失效。
// ❌ 錯誤示範
LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
LinearLayout ll = (LinearLayout) inflater.inflate(R.layout.activity_main, null);
ll.setBackgroundColor(Color.BLACK); // 設定給暫時的 View
setContentView(R.layout.activity_main); // 重新 inflate,前面設定失效
// ✅ 正確示範
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); // 先設定佈局
LinearLayout ll = findViewById(R.id.your_linearlayout_id); // 從佈局取得實例
ll.setBackgroundColor(Color.BLACK); // 對實際顯示的 View 設定
}
setContentView(),再 findViewById():確保操作的是螢幕上顯示的 View 實例。LinearLayout 必須有 android:id 屬性。setContentView(view) 直接傳入已設定好的 View,而非資源 ID。LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
ll.setBackgroundColor(Color.BLACK);
ll.setLayoutParams(new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT));
setContentView(ll); // 直接將動態建立的 View 設為內容視圖