在 LinearLayout 中動態添加 TableLayout 和 Button 時,若 TableLayout 高度為 wrap_content 且內容較多,Button 可能被擠出可視區域。解決方法是改用 RelativeLayout 精確控制位置關係。
問題佈局 (LinearLayout)
問題:TableLayout 內容多時佔滿空間,Button 推到屏幕外。
解決方案:RelativeLayout
關鍵屬性解析
| 屬性 | 作用 |
| layout_alignParentTop="true" | 頂部對齊父佈局頂部 |
| layout_below="@id/itemTable" | 此視圖頂部在 itemTable 底部下方 |
| layout_centerHorizontal="true" | 水平居中 |
| layout_above="@id/btn" | 此視圖底部在 btn 頂部上方 (反向) |
代碼動態實現
RelativeLayout container = new RelativeLayout(this);
RelativeLayout.LayoutParams containerParams = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
TableLayout table = new TableLayout(this);
RelativeLayout.LayoutParams tableParams = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
tableParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
table.setLayoutParams(tableParams);
// 添加表格行...
Button btn = new Button(this);
RelativeLayout.LayoutParams btnParams = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
btnParams.addRule(RelativeLayout.BELOW, table.getId());
btnParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
btnParams.topMargin = dpToPx(10);
btn.setLayoutParams(btnParams);
container.addView(table);
container.addView(btn);
現代替代:ConstraintLayout (性能更好)
選擇建議
- 簡單垂直堆疊:
LinearLayout + layout_weight 分配空間
- 固定相對位置:
RelativeLayout 或 ConstraintLayout
- 複雜響應式佈局:
ConstraintLayout (扁平層級、性能最優)
- 動態列表:
RecyclerView (而非手動添加 View)
- 上一篇文章: Android 解析服務器響應判斷 JSONObject 與 JSONArray 的方法
- 下一篇文章: iOS 根據價格字段對字典數組進行排序的正確方法
Copyright ©
程式碼之家 All Rights Reserved