Android:在绘制之前获取视图的高度 [英] Android: get height of a view before it´s drawn

查看:18
本文介绍了Android:在绘制之前获取视图的高度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于动画,我需要知道视图的高度.问题是,除非绘制了视图,否则 getHeight() 方法始终返回 0.那么有没有什么办法不用画就可以得到高度呢?

For an animation I need to know the height from a View. The Problem is, that the getHeight() method allways return 0 unless the View is drawn. So is there any way to get height without drawing it?

在这种情况下,View 是一个 LinearLayout.

In this case the View is a LinearLayout.

我尝试改编 https://github 中的展开动画.com/Udinic/SmallExamples/blob/master/ExpandAnimationExample/src/com/udinic/expand_animation_example/ExpandAnimation.java

有了它,我想为列表项扩展更多信息.我无法通过 xml 实现相同的效果.目前,动画仅在您在绘制之前知道布局大小时才起作用.

With it I want to expand some more informations for a list item. I wasn´t able to achieve the same effect via xml. At the moment the Animation only works when you know the layout size before drawing it.

推荐答案

听起来您想要获取高度但在视图可见之前隐藏它.

Sounds like you want to get the height but hide the view before it is visible.

首先将视图中的可见性设置为可见或不可见(这样就可以创建高度).别担心,我们会在代码中将其更改为 invisible/gone,如下所示:

Have the visibility in the view set to visible or invisible to start with(just so that a height is created). Don't worry we will change it to invisible/gone in the code as shown below:

private int mHeight = 0;
private View mView;

class...

// 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();  // Ahaha!  Gotcha

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

});

这篇关于Android:在绘制之前获取视图的高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆