get ConstraintLayout height and width

1.5k Views Asked by At

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);
}
1

There are 1 best solutions below

0
BabyishTank On

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()

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        myView = view.findViewById(R.id.rtt); # your constraint layout
        view.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
            @Override
            public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
                int height = bottom - top;
                int width = right - left;
                Log.i("LOG", "height is" + height);
                Log.i("LOG", "width is " + width);
            }
        });
    }

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.