Android通过代码添加和调整布局控件

概述

在实际开发中,有时候布局控件的添加和修改是需要动态调整的,参数的设置和方法的调用显得非常重要,可能xml布局文件中一个小功能,通过代码需要绕一圈来实现,如:margin 边距

动态添加布局

//实例化根布局
ConstraintLayout layout = new ConstraintLayout(context);
//取得根布局控件并设置参数
View view = layout.getRootView();
view.setPadding(5, 5, 5, 0);
//绑定布局
setContentView(view);

动态添加控件

这里以添加两个上下位置的TextView为例,你也可以添加所有你想要的控件
重点在于控件的定位需要根据id值来控制
其他的控件的参数设置根据需要来设定即可,基本上同xml布局控件时差不多

//因为是约束布局,通过id值来控制约束控件的定位
int id = 1;   
//添加一个TextView
TextView textView = new TextView(context);
textView.setId(id);
textView.setText("我是第一个TextView");
textView.setTextSize(21);
textView.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
textView.setBackground(context.getDrawable(R.drawable.bg_radius_green));
ConstraintLayout.LayoutParams layoutParams = new ConstraintLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
layout.addView(textView, layoutParams);
id++;
textView = new TextView(context);
textView.setId(id);
textView.setText("我是第二个TextView");
textView.setTextSize(16);
textView.setBackground(context.getDrawable(R.drawable.bg_radius_green));
textView.setPadding(9, 0, 0, 0);
layoutParams = new ConstraintLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
//设置定位
layoutParams.topToBottom = id - 1;
layoutParams.topMargin = 9;
layout.addView(textView, layoutParams);

动态设置 View 尺寸

有时我们需要通过代码来调整控件的大小,需要借助其 LayoutParams 来实现动态调整其 width 和 height 的值

//获取view 的布局参数
ViewGroup.LayoutParams layoutParams = mView.img.getLayoutParams();
//设置宽度,也可自定义
layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
//设置高度
layoutParams.height = convertDpToPixel(480);;
//重新给view设置布局参数
mView.img.setLayoutParams(layoutParams);

动态变更位置

有时我们需要根据控件的添加和大小的设置而动态变更控件的位置,同样需要借助其 LayoutParams 来实现

RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) mView.img.getLayoutParams();
layoutParams.leftMargin = 10;
layoutParams.topMargin = 500;
mView.img.setLayoutParams(layoutParams);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值