1如果一个自定义view要在短时间被多次调用,会造成多次读取xml和findViewById,所以动态添加控件、属性

RelativeLayout:

private void initView() {
Button btn1 = new Button(this.getContext());
btn1.setId(1);
RelativeLayout.LayoutParams params1 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params1.addRule(ALIGN_PARENT_LEFT);
btn1.setText("1");
this.addView(btn1,params1);

Button btn2 = new Button(this.getContext());
btn2.setId(2);
RelativeLayout.LayoutParams params2 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params2.addRule(RIGHT_OF,btn1.getId());
btn2.setText("2");
this.addView(btn2,params2);

Button btn3 = new Button(this.getContext());
btn3.setId(3);
RelativeLayout.LayoutParams params3 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params3.addRule(RIGHT_OF,btn2.getId());
btn3.setText("3");
this.addView(btn3,params3);

this.setLayoutParams(new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT));
}

 

不setId的话,getId默认返回-1,无法使用RIGHT_OF