在使用addView方法添加控件时,需要将要添加的控件的LayoutParams赋值后再添加,否则LayoutParams会被忽略。示例如下:
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); Button button = new Button(context); // 设置button的LayoutParams button.setLayoutParams(params);
// 将button添加到LinearLayout中 LinearLayout linearLayout = findViewById(R.id.linear_layout); linearLayout.addView(button);