码迷,mamicode.com
首页 > 其他好文 > 详细

为节省内存,动态添加view布局和控件

时间:2015-03-02 22:14:47      阅读:283      评论:0      收藏:0      [点我收藏+]

标签:

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

为节省内存,动态添加view布局和控件

标签:

原文地址:http://www.cnblogs.com/Ringer/p/4309727.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!