【发布时间】:2021-06-30 07:01:59
【问题描述】:
我想创建一个基于parent 的height 和width 计算边距值的方法。下面的代码为height 和width 输出-1。如何正确获取父母的高度和宽度?
@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);
}
【问题讨论】:
-
父ConstraintLayout的宽高是否设置为MATCH_PARENT? MATCH_PARENT 的常量是 -1 我还怀疑您可能在计算 UI 大小之前调用此函数太早了您可能希望在 onMeasure() stackoverflow.com/a/23358330/5777189 期间获取实际运行时大小
-
@BabyishTank 是的,父母的宽度和高度设置为 MATCH_PARENT。该函数在片段的
onActivityCreated()方法中调用。
标签: android android-studio android-layout android-constraintlayout layoutparams