繁体   English   中英

获取视图的高度 - 变量需要声明为 final

[英]Get height of a view - Variable needs to be declared final

我想使用 TreeObserver 方法获取视图的高度:

        int v1_h;
        v1.getViewTreeObserver().addOnGlobalLayoutListener(newViewTreeObserver.OnGlobalLayoutListener() {
            @SuppressLint("NewApi")
            @SuppressWarnings("deprecation")
            @Override
            public void onGlobalLayout() {
                //now we can retrieve the width and height

                v1_h = v1.getHeight();


                if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN)
                    v1.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                else
                    v1.getViewTreeObserver().removeGlobalOnLayoutListener(this);
            }
        });

//Do something with v1_h later on

我想将高度存储在一个变量中并稍后使用。 问题是它需要声明 final 才能从内部类中访问。 所以我把它定为最终的,但现在它说它不能被分配。 有想法该怎么解决这个吗?

最简单的方法是将变量声明为类成员,而不是在堆栈上声明的变量。 如果您将 v1_h 设为 final,您将无法真正按照您期望的方式使用它。

实际上v1_h和你创建的内部类“ new ViewTreeObserver.OnGlobalLayoutListener()... ”在同一个范围内,如果你想改变v1_h的值你应该把声明移到范围的上一层,我不知道你的代码到底是怎么回事,但我举了一个例子来理解我在说什么:

public class MainActivity extends Activity {
//The scope you should declare your variable in, No need to declare as a final
//Here is an upper level scope than inner class's!
int v1_h;

@Override
    protected void onCreate(Bundle savedInstanceState) {
    ...
    //1.The scope you declared your variable in 
    //2.Where the inner class is
        v1.getViewTreeObserver().addOnGlobalLayoutListener(...)
    //1 && 2 => They were in the same scope in your code
    ...
    }
}

希望它有帮助...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM