java代码动态布局
Contents
2015-09-30 15:18:08
动态布局的基本知识
ViewGroup.LayoutParams 设置的是子控件的属性
Gravity 设置显示位置
addView (RelativeLayout专有)将控件添加到父控件里
setMargins 设置外边距
addRule(属性,相对控件的id)
实现步骤:
- 创建一个LayoutParams对象 lp,并且初始化控件 的大小。
- 通过上述属性对象lp 设置外边距,内边距等属性。
- 子控件用过setLayoutParams方法设置上述属性。
- 将子控件添加到父控件即可。
示例代码:
linearLayout = (LinearLayout)findViewById(R.id.llTest);
ImageView imageView = new ImageView(this);
//此处LinearLayout必须与xml布局中定义的llTest一直,否则会报转型错误。
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(50,50);
params.setMargins(15, 0, 15, 0);
params.gravity = Gravity.CENTER;
imageView.setLayoutParams(lp);
linearLayout.addView(imageView);
–
View actionBar = findViewById(R.id.action_bar);
RelativeLayout rlTest = new RelativeLayout(this);
int matchParent = RelativeLayout.LayoutParams.MATCH_PARENT;
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(matchParent, matchParent);
params.addRule(RelativeLayout.BELOW, actionBar.getId());
rlTest.setPadding(10, 10, 10, 10);
rlTest.setLayoutParams(params);
((ViewGroup) actionBar.getParent()).addView(rlTest);
ImageView iv = new ImageView(this);
iv.setImageResource(R.color.common_gray_line_color);
RelativeLayout.LayoutParams ivParams = new RelativeLayout.LayoutParams(122, 122);
iv.setLayoutParams(ivParams);
rlTest.addView(iv);
int ivId = iv.getId();
iv.setId(iv.hashCode());
ivId = iv.getId();
ImageView ivAdd = new ImageView(this);
ivAdd.setImageResource(R.drawable.personal_profile_icon_add_img);
ivAdd.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
ivAdd.setBackgroundResource(R.color.common_gray_line_color);
RelativeLayout.LayoutParams ivAddParams = new RelativeLayout.LayoutParams(122, 122);
ivAddParams.addRule(RelativeLayout.RIGHT_OF, iv.getId());
ivAddParams.setMargins(8, 0, 0, 0);
rlTest.addView(ivAdd, ivAddParams);