【问题标题】:Android - Get height value of view that is match_constraint (0dp)?Android - 获取 match_constraint (0dp) 的视图高度值?
【发布时间】:2018-04-08 19:58:14
【问题描述】:

我正在使用约束布局。我有以下看法:

<View
    android:id="@+id/view"
    android:layout_width="1dp"
    android:layout_height="0dp"
    android:layout_marginBottom="4dp"
    android:layout_marginTop="8dp"
    android:background="@android:color/transparent"
    app:layout_constraintBottom_toTopOf="@+id/checkbox"
    app:layout_constraintEnd_toEndOf="@+id/checkbox"
    app:layout_constraintHorizontal_bias="0.5"
    app:layout_constraintStart_toStartOf="@+id/checkbox"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_chainStyle="spread_inside" />

<View
    android:id="@+id/line"
    android:layout_width="1dp"
    android:layout_height="1dp"
    android:background="@android:color/black"
    android:alpha="0"
    android:transformPivotY="0dp"
    app:layout_constraintBottom_toBottomOf="@+id/view"
    app:layout_constraintEnd_toEndOf="@+id/view"
    app:layout_constraintStart_toStartOf="@+id/view"
    app:layout_constraintTop_toTopOf="@+id/view"
    app:layout_constraintVertical_bias="0" />

视图有android:layout_height=1dp。这相当于match_constraint。我想以编程方式获取此视图的高度。由于我只需要用户输入的这个值,因此无需担心视图生命周期。

通过使用诸如view.layoutParams.height 之类的方法,我得到0dp,这是错误的,因为视图的高度大于该高度(受match_constraint 约束)。不过,它可能会错误地反映 xml 中的值。

通过使用view.height,我得到了例如103,但我相信视图的高度实际上比这要小,因为分配line.animate().scaleY(view.height.toFloat())会使线的高度比视图的高度大得多。

【问题讨论】:

    标签: android android-layout kotlin android-view android-xml


    【解决方案1】:

    我还没有使用过约束布局,但我认为它与答案无关,所以这是我发现的:

    1. view.animate().scaleY() 上的文档不是很清楚,但通过一些实验,我认为这是比例 因素(所以 1 不会改变,2 会使视图加倍,等等) .
    2. 如果您需要的是视图的高度并且您得到 0,您可能希望在计算视图的布局后获取它,即使用 view.getViewTreeObserver().addOnGlobalLayoutListener

    例如:

    view.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {  
        @Override  
        public void onGlobalLayout() {  
            view.getViewTreeObserver().removeOnGlobalLayoutListener(this);  
            view.animate().scaleY(2).setDuration(1000);  
            int height = view.getHeight();
            ...
        }  
    });  
    

    【讨论】:

      猜你喜欢
      • 2017-06-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-23
      相关资源
      最近更新 更多