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

  • Post author:
  • Post category:其他




概述

在实际开发中,有时候布局控件的添加和修改是需要动态调整的,参数的设置和方法的调用显得非常重要,可能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);



版权声明:本文为ymtianyu原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。