1

I'm developing a little game and I need to give different ImageViews different LayoutParams. Therefore I created an array ConstraintLayoutParams. After changing the properties of the layoutparams seperately, all the layoutparams have the same properties than the last one. So thet keep overwriting themselves.

 p[0] = (ConstraintLayout.LayoutParams) card2.getLayoutParams();     
 p[0].startToStart=R.id.plazertxt1;
Toast.makeText(getApplicationContext(),String.valueOf(p[0].startToStart),Toast.LENGTH_LONG).show();  
 // shows 2131165282
        p[1] = (ConstraintLayout.LayoutParams) card2.getLayoutParams();
        p[1].startToStart=R.id.plazertxt2;
        p[2] = (ConstraintLayout.LayoutParams) card2.getLayoutParams();
        p[2].startToStart=R.id.plazertxt3;
        p[3] = (ConstraintLayout.LayoutParams) card2.getLayoutParams();
        p[3].startToStart=R.id.plazertxt4;
  Toast.makeText(getApplicationContext(),String.valueOf(p[0].startToStart)+","+String.valueOf(p[1].startToStart)+","+String.valueOf(p[2].startToStart)+","+String.valueOf(p[3].startToStart)+",",Toast.LENGTH_LONG).show();
//shows 2131165285,2131165285,2131165285,2131165285

The expected outcome for the last Toast should be

"2131165282,2131165283,2131165284,2131165285"

But it is

"2131165285,2131165285,2131165285,2131165285"
MD Naseem Ashraf
  • 1,030
  • 2
  • 9
  • 22
Brockaaa
  • 13
  • 2

1 Answers1

0

The following statement all return the same structure. You don't get a new layout params for each call to getLayoutParams().

p[1] = (ConstraintLayout.LayoutParams) card2.getLayoutParams();
p[2] = (ConstraintLayout.LayoutParams) card2.getLayoutParams();
p[3] = (ConstraintLayout.LayoutParams) card2.getLayoutParams();

So, after these three lines p[1] == p[2] == p[3]. When the following lines execute:

p[1].startToStart=R.id.plazertxt2;
p[2].startToStart=R.id.plazertxt3;
p[3].startToStart=R.id.plazertxt4;

then p[1] == p[2] == p[3] == R.id.plazertxt4 since p[3].startToStart=R.id.plazertxt4 is the last to execute.

It's a little confusing, but that's what is going on. You should avoid using layout params for constraint setting but use ConstraintSet instead.

This class allows you to define programmatically a set of constraints to be used with ConstraintLayout. It lets you create and save constraints, and apply them to an existing ConstraintLayout.

Cheticamp
  • 61,413
  • 10
  • 78
  • 131