KalaBalik KalaBalik - 3 years ago 134
Android Question

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

In a

, how can I programmatically get a
to which my
is connected, provided that I have both views' ids and that I know how my
is connected to the other
(for example,
)? I want to swap two (not necessarily connected!) views in my layout.

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

// 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);

To be clear: There are four
s involved here:

  • The two views I want to swap. They can, but need not be connected in any way.

  • The view that my first view is connected to; this is the one I want my second view to be connected to.

  • And the view that my second view is connected to; this is the one I want my first view to be connected to.

Think: In a chess board I want to swap two corners. I have their ids and I know that each of their tops are connected to some other view.

Answer Source

If you know the type of connection such as layout_constraintTop_toTopOf or layout_constraintTop_toBottomOf then you can use the layout params as follows:

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

You can look at the documentation for ConstraintLayout.LayoutParams for more information.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download