如何在Android中使用ConstraintSet水平堆叠TextView?

时间:2017-05-06 22:56:25

标签: android android-layout android-constraintlayout

我现在已经四处寻找关于如何以编程方式添加和保留TextViews的方法,并且由于某些原因我无法让它工作。我已经查看了其他answers以及您应该添加约束的建议顺序,但这对我不起作用。

使用我当前的解决方案,TextViews会像this一样叠加。我的目标是让它像this一样分开。

我目前的代码如下:

// Get all the existing assignments and list them
Assignment[] currentAssignments = Assignment.getAssignments();
// Get the layout that will hold the assignments
ConstraintLayout layout = (ConstraintLayout) findViewById(R.id.mainLayout);
// Loop through each assignment, creating a TextView and getting information for each one
for (int i = 0; i < currentAssignments.length; i++) {
    // Create new TextView and set properties
    TextView newTextView = new TextView(this);
    newTextView.setId(i);
    newTextView.setLayoutParams(new ConstraintLayout.LayoutParams(ConstraintLayout.LayoutParams.WRAP_CONTENT, ConstraintLayout.LayoutParams.WRAP_CONTENT));
    newTextView.setText(currentAssignments[i].getAssignmentName() + "\nHand in date: " + currentAssignments[i].getAssignmentHandInDate());
    newTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 25);
    // Add to layout
    layout.addView(newTextView);
}
// Set up a new ConstraintSet so we can constrain all the assignments
ConstraintSet set = new ConstraintSet();
// Clone the current layout
set.clone(layout);
// Loop through previously added assignments in layout and connect them
for (int i = 0; i < layout.getChildCount(); i++) {
    // Setup new constraints to place on screen properly
    if (i > 0) {
        // If assignment is not the first to be added, link it to the previously added assignment
        set.connect(i, ConstraintSet.TOP, i - 1, ConstraintSet.BOTTOM, 8);
    }
    else {
        // If the assignment is the first to be added link it to the top of the layout
        set.connect(i, ConstraintSet.TOP, layout.getId(), ConstraintSet.TOP, 8);
    }
}
// Apply changed layout to actual layout
set.applyTo(layout);

我的问题:

如何以编程方式在ConstraintLayout中水平布局TextView?

感谢您阅读!

0 个答案:

没有答案