代码控制约束布局ConstraintLayout

时间:2025-03-28 16:02:20

实例化布局

同其他布局一样,new 一个根布局出来用来放置控件

ConstraintLayout layout = new ConstraintLayout(mContext);

控件定位约束

控件的定位和约束控制需要借助 来设置,在设置约束时,要知道所参考的控件的 ID 值,如果是自定义的控件,记得给控件加上 setId()

定位参考父布局

首先要拿到根布局的ID值,在xml中我们直接使用 parent 在代码里,也有相对应的ID值
.PARENT_ID

ConstraintLayout.LayoutParams layoutParams = new ConstraintLayout.LayoutParams(ConstraintLayout.LayoutParams.WRAP_CONTENT, ConstraintLayout.LayoutParams.WRAP_CONTENT);
layoutParams.startToStart = ConstraintLayout.LayoutParams.PARENT_ID;
layoutParams.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
layoutParams.topToTop = ConstraintLayout.LayoutParams.PARENT_ID;

参考代码添加的控件

以下是伪代码,只作说明怎么设置参考的id值,完整代码在另一篇 通过代码添加和调整布局控件

int id = 1;   
//添加一个TextView
TextView textView = new TextView(context);
textView.setId(id);
id++;
textView = new TextView(context);
textView.setId(id);
//设置定位
layoutParams.topToBottom = id - 1;
layoutParams.topMargin = 9;

返回定义好的布局

() 即可拿到我们设置好的布局

return layout.getRootView();

完整代码参考

ConstraintLayout layout = new ConstraintLayout(mContext);
TextView textView = new TextView(mContext);
textView.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
textView.setText(String.valueOf(mList.get(i)));
textView.setTextSize(16);
textView.setTypeface(Typeface.DEFAULT_BOLD);
textView.setPadding(5, 9, 5, 9);
ConstraintLayout.LayoutParams layoutParams = new ConstraintLayout.LayoutParams(ConstraintLayout.LayoutParams.WRAP_CONTENT, ConstraintLayout.LayoutParams.WRAP_CONTENT);
layoutParams.startToStart = ConstraintLayout.LayoutParams.PARENT_ID;
layoutParams.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
layoutParams.topToTop = ConstraintLayout.LayoutParams.PARENT_ID;
layout.addView(textView, layoutParams);
return layout.getRootView();

TextView设置加粗

这个不怎么用,一直找不到方法,最后发现是放在 Typeface 里,提醒一下有需要的朋友

textView.setTypeface(Typeface.DEFAULT_BOLD);