getHeight for View哪个可见性=已消失

rev*_*ary 8 android android-ui android-animation android-layout android-view

我有一个LinearLayout默认情况下其可见性设置为"Gone",我需要获取此视图的高度,以便在可见时执行滑出动画.如何获得可见状态的总高度,因为View.getHeight在未调用布局时返回零.

<LinearLayout
    android:id="@+id/card_checkin_layout_termsconditionsconfirmation"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginLeft="4dp"
    android:layout_marginRight="4dp"
    android:gravity="center_horizontal"
    android:background="#d0d0d0"
    android:visibility="invisible"
    android:orientation="vertical" >

    <Button
        android:id="@+id/card_checkin_button_confirmdetails"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="8dp"
        android:background="@drawable/shape_checkin_buttons2"
        android:text=">   Confirm your details"
        android:paddingLeft="8dp"            
        android:gravity="left|center_vertical"
        android:textColor="@color/card_checkin_button_textcolor_blue" 
        />

    <Button
        android:id="@+id/card_checkin_button_termsandconditions"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginBottom="8dp"
        android:paddingLeft="8dp"            
        android:background="@drawable/shape_checkin_buttons2"
        android:text=">   Terms and Conditions"
        android:gravity="left|center_vertical"
        android:textColor="@color/card_checkin_button_textcolor_blue" 
        />

</LinearLayout>
Run Code Online (Sandbox Code Playgroud)

Rit*_*une 11

最初将视图的可见性设置为可见或不可见,以便计算高度.后来改变了能见度.

仅供参考:removeGlobalOnLayoutListener()自API级别16以来已被弃用,它被替换为removeOnGlobalLayoutListener().

你可以试试这个:

// onCreate or onResume or onStart ...
mView = findViewByID(R.id.someID);
mView.getViewTreeObserver().addOnGlobalLayoutListener( 
    new OnGlobalLayoutListener(){

        @Override
        public void onGlobalLayout() {
            // gets called after layout has been done but before display
            // so we can get the height then hide the view    

            mHeight = mView.getHeight();  

            mView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
            mView.setVisibility(View.GONE);
        }

});
Run Code Online (Sandbox Code Playgroud)

  • 只是为了澄清,`removeGlobalOnLayoutListener()`只是由于命名错误而被弃用.在API> = 16时使用(现在)仍然是安全的,但我建议制作一个静态实用程序方法,调用OnGlobal用于API 16及更高版本,以及GlobalOn用于更低级别. (4认同)