動態建立視圖兩大核心類
LayoutParams:指定視圖在父容器中的尺寸與規則(LinearLayout.LayoutParams、RelativeLayout.LayoutParams、ViewGroup.LayoutParams)。
ViewGroup.addView(View, index, LayoutParams):插入指定位置。
完整 Activity 範例
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.friend_info_view); // 包含一個 LinearLayout (id: groups)
LinearLayout container = findViewById(R.id.groups);
// ---------- 第 1 組:常用聯系人 ----------
TextView tv1 = new TextView(this);
tv1.setText("常用聯系人");
tv1.setId(View.generateViewId());
tv1.setBackgroundResource(R.color.group_view_background);
// RelativeLayout 規則:置於 groups 下方
RelativeLayout.LayoutParams lp1 = new RelativeLayout.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
lp1.addRule(RelativeLayout.BELOW, R.id.groups);
tv1.setLayoutParams(lp1);
// 建立 ListView 並設定 Adapter
ListView lv1 = new ListView(this);
List
關鍵技巧總結
- LinearLayout 插入位置:
addView(child, index) 精確控制順序;indexOfChild(existingView) 取得現有視圖索引,實現「標題後插入列表」。
- RelativeLayout 規則:
addRule(RelativeLayout.BELOW, anchorId)、ALIGN_PARENT_BOTTOM 等,需視圖已有 ID(View.generateViewId() 動態生成)。
- LayoutParams 型別必須匹配父容器:父容器是 LinearLayout → 用 LinearLayout.LayoutParams;父容器是 RelativeLayout → 用 RelativeLayout.LayoutParams。
- 動態 ID:API 17+ 使用
View.generateViewId() 避免衝突。
- 移除視圖:
container.removeView(child) 或 removeViewAt(index)。
效能與維護建議
- 大量動態視圖改用
RecyclerView + 多型別 ViewHolder,效能與維護性遠優於手動 addView。
- 複雜佈局優先用 XML
<include>/<merge> + ViewStub 延遲膨脹。
- 動態建立視圖邏輯封裝為工具方法或自訂 ViewGroup,避免 Activity 過度膨脹。
動態佈局適合簡單、條件式 UI;複雜列表請拥抱 RecyclerView。