我想像Google一样创建日历日视图。 为此,我想动态创建时间轴。这就是我现在这样做的方式:
TextView nextTime = new TextView(this);
View nextView = new View(this);
View nextLine = new View(this);
ConstraintLayout.LayoutParams lineParams = new
ConstraintLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT);
ConstraintLayout.LayoutParams timeParams = new
ConstraintLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT);
ConstraintLayout.LayoutParams viewParams = new
ConstraintLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT);
viewParams.topToBottom = firstView.getId();
viewParams.leftToLeft = firstView.getId();
viewParams.height = Utils.changeDPItoPX(26, displayMetrics);
viewParams.width = Utils.changeDPItoPX(0, displayMetrics);
viewParams.setMargins(0, Utils.changeDPItoPX(16, displayMetrics),0,0);
nextView.setLayoutParams(viewParams);
constraintLayout.addView(nextView);
timeParams.topToTop = nextView.getId();
timeParams.bottomToBottom = nextView.getId();
timeParams.leftToLeft = nextView.getId();
timeParams.width = ViewGroup.LayoutParams.WRAP_CONTENT;
timeParams.height = ViewGroup.LayoutParams.WRAP_CONTENT;
timeParams.setMargins(Utils.changeDPItoPX(16, displayMetrics), 0,0,0);
nextTime.setLayoutParams(timeParams);
constraintLayout.addView(nextTime);
lineParams.height = Utils.changeDPItoPX(2, displayMetrics);
lineParams.bottomToBottom = nextTime.getId();
lineParams.endToEnd = nextView.getId();
lineParams.startToEnd = nextTime.getId();
lineParams.topToTop = nextTime.getId();
lineParams.setMargins(Utils.changeDPItoPX(8, displayMetrics), 0,
Utils.changeDPItoPX(8, displayMetrics), 0);
lineParams.width = Utils.changeDPItoPX(0, displayMetrics);
nextLine.setLayoutParams(lineParams);
constraintLayout.addView(nextLine);
在我的布局xml中,我已经拥有了第一个时间戳。所以这段代码应该添加下一个。它看起来像这样:
| 00:00 -------------------------- |
| 01: - 0--0 ----------------------- |
timeLine超过我的时间,它也会进入屏幕的末尾。 但它应该看起来像上面的timeStamp。
我做错了什么?为什么忽略约束?
答案 0 :(得分:0)
使用ConstraintSet而不是Layout params将视图添加到ConstraintLayout。
您可以参考以下链接以了解如何使用ConstraintSet
https://developer.android.com/reference/android/support/constraint/ConstraintSet.html
答案 1 :(得分:0)
好的,我明白了。因此,当您想要动态添加视图然后将其约束到其他视图时,您基本上必须执行的操作是:
constraintLayout = (ConstraintLayout) findViewById(R.id.mainframe);
View firstView = findViewById(R.id.firstView);
View nextView = new View(this);
nextView.setBackgroundColor(0xFF00FF00);
constraintLayout.addView(nextView);
constraintSet.clone(constraintLayout);
constraintSet.connect(nextView.getId(),ConstraintSet.TOP,
firstView.getId(), ConstraintSet.BOTTOM, 16);
constraintSet.applyTo(constraintLayout);
如果有人遇到同样的问题,我希望我可以提供帮助。