I have seen in the following answer: https://stackoverflow.com/a/24035591 of another post that to get the width of an element after the drawing phase I can do the following:
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_activity);
View view1,view2;
int width1,width2;´
view1.post(() -> {
width1=view1.getWidth();
}
}
What if I want to get the width of 2 elements (view1 and view2) instead of only one element as I am using both values in the same mathematical formula?
Should I do this? -->
view1.post(() -> {
width1=view1.getWidth();
width2=view2.getWidth();
formula(width1,width2);
}
Or should I do this(I don't know if it is okay to put a runnable inside another runnable) -->
view1.post(() -> {
width1=view1.getWidth();
view2.post(() -> {
width2=view2.getWidth();
formula(width1,width2);
}
}
I can't do the following as I need both width's to be used in the same formula:
view1.post(() -> {
width1=view1.getWidth();
}
view2.post(() -> {
width2=view2.getWidth();
}
Both of the possibilities are working, but I would like to know which one is better or if there is another option to get both width's as I need them together as I am using them in one mathematical formula.
Note that formula(x,y) will use both width's to setMargins of another element:
TextView text1;
formula(x,y){
int z = x + y;
ConstraintLayout.LayoutParams params =
(ConstraintLayout.LayoutParams) text1.getLayoutParams();
params.setMargins(0,z,0,0);
text1.setLayoutParams(params);
}
EDIT:
what I have in OnCreate:
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_activity);
/*I set margins of view1 and view2 so that the width of both
is changing (this is why if I call getWidth of view1 and view2 in this
method, it will take the very first width (the width without the new
margins) */
ConstraintLayout.LayoutParams params1 =
(ConstraintLayout.LayoutParams) view1.getLayoutParams();
params1.setMargins(X,0,X,0);
view1.setLayoutParams(params1);
ConstraintLayout.LayoutParams params2 =
(ConstraintLayout.LayoutParams) view2.getLayoutParams();
params2.setMargins(X,0,X,0);
view2.setLayoutParams(params2);
//X is a non-static value
}