【问题标题】:get ConstraintLayout height and width获取 ConstraintLayout 的高度和宽度
【发布时间】:2021-06-30 07:01:59
【问题描述】:

我想创建一个基于parentheightwidth 计算边距值的方法。下面的代码为heightwidth 输出-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


【解决方案1】:

这里有几个问题,parms.height 会给你这个值 (https://developer.android.com/reference/android/view/ViewGroup.LayoutParams#MATCH_PARENT),它是 -1。不是您要查找的约束布局的像素高度。

此外,您不能在系统呈现视图之前在视图上使用宽度/高度/getMeasuredWidth/getMeasuredHeight(通常来自 onCreate/onResume)。但是您可以设置一个侦听器,以在系统为 MATCH_PARENT 计算像素后获取该值。 在片段的 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);
            }
        });
    }

无论如何,请注意您只有在视图呈现后才能获得此值。此时视图已经渲染,您可能无法编辑边距。您可能需要重新考虑您的方法。

【讨论】:

    猜你喜欢
    • 2017-12-26
    • 1970-01-01
    • 2012-10-10
    • 1970-01-01
    • 1970-01-01
    • 2010-11-18
    • 2023-04-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多