在 ConstraintLayout 中,确定我的视图连接到的视图(例如,通过 ConstraintSet.TOP)

In a ConstraintLayout, determine the view my view is connected to (via ConstraintSet.TOP, for example)

ConstraintLayout 中,如果我有两个视图的 ID 并且我知道我的 View 连接到另一个 View(例如,ConstraintSet.TOP)?我想在我的布局中交换两个(不一定连接!)视图。

void swapViews(ConstraintLayout constraintLayout, int view1ID, int view2ID) {
    ConstraintSet constraintSet = new ConstraintSet();
    constraintSet.clone(constraintLayout);

    // How do I get the "anchor" or "connectedView" of a view with a specific constraint?
    // Something like the following:
    // int anchor1 = this.findViewById(view1ID).get...(ConstraintSet.TOP);
    // int anchor2 = this.findViewById(view2ID).get...(ConstraintSet.TOP);

    constraintSet.connect(view2ID, ConstraintSet.TOP, anchor1, ConstraintSet.TOP);
    constraintSet.connect(view1ID, ConstraintSet.TOP, anchor2, ConstraintSet.TOP);
    constraintSet.applyTo(constraintLayout);
}

要清楚:这里涉及四个 View

思考:在棋盘上我想交换两个角。我有他们的 ID,我知道他们的每个顶部都连接到其他视图。

如果您知道 layout_constraintTop_toTopOflayout_constraintTop_toBottomOf 等连接类型,则可以按如下方式使用布局参数:

View v = findViewById(R.id.viewYouAreInterestedIn);
ConstraintLayout.LayoutParams lp = (ConstraintLayout.LayoutParams) v.getLayoutParams();
int topConnectionId = lp.topToTop;

您可以查看 ConstraintLayout.LayoutParams 的文档了解更多信息。