其实控件在代码中也能设置他的属性:
/**
* 在代码中设置控件属性
*/
private void initView() {
//在代码中设置
layout=(LinearLayout) findViewById(R.id.linear);
layout.addView(creatrView("张三"));
layout.addView(creatrView("李四"));
}
private View creatrView(String string) {
//设置主布局的宽高
LinearLayout.LayoutParams lp=new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
LinearLayout linearLayout=new LinearLayout(this);
linearLayout.setLayoutParams(lp);
linearLayout.setOrientation(LinearLayout.VERTICAL);
//设置子控件的属性
ViewGroup.LayoutParams vlp1=new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
ViewGroup.LayoutParams vLP2=new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
TextView text1=new TextView(this);
TextView text2=new TextView(this);
text1.setPadding(50, 0, 0, 0);
text1.setLayoutParams(vlp1);
text2.setLayoutParams(vLP2);
text1.setText("姓名:");
text2.setText(string);
linearLayout.addView(text1);
linearLayout.addView(text2);
return linearLayout;
}