I want to make a method that computes the margin values based on the parent's height and width. The code below outputs -1 for both height and width. How can I get the parent's height and width properly?
@RequiresApi(api = Build.VERSION_CODES.R)
public void setMarginsPercentages(Context context, @NotNull ConstraintLayout parent, @NotNull Object object, double leftPercentage, double topPercentage, double rightPercentage, double bottomPercentage) {
FrontEndObject item = getObjectType(object);
ConstraintLayout.LayoutParams params = new ConstraintLayout.LayoutParams(parent.getLayoutParams());
int height = params.height; //outputs -1
int width = params.width; //outputs -1
int left = (int) (leftPercentage * width);
int right = (int) (rightPercentage * width);
int top = (int) (topPercentage * height);
int bottom = (int) (bottomPercentage * height);
item.setMargins(parent, object, left, top, right, bottom);
}
There are couple problems here, the parms.height will give you this value (https://developer.android.com/reference/android/view/ViewGroup.LayoutParams#MATCH_PARENT), which is -1. Not the constraint layout's height in pixel you are looking for.
Also, You cannot use the width/height/getMeasuredWidth/getMeasuredHeight on a View before the system renders it (typically from onCreate/onResume). But you could set a listener, to get the value after the system calculate the pixel for the MATCH_PARENT. Try this at your fragment's onViewCreated()
Anyway, notice you only get this value after the view is rendered. At this point the view is already rendered, you might not be able to edit the margin. You might want to rethink your approach.