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

时间:2016-04-07 22:31:39

标签: java android view height

我想使用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才能从内部类中访问。所以我说它是最终的,但现在它说它不能被分配。有想法该怎么解决这个吗?

2 个答案:

答案 0 :(得分:1)

最简单的方法是将变量声明为类成员而不是在堆栈上声明的变量。如果你让v1_h成为最终版,你将无法以你期望的方式使用它。

答案 1 :(得分:0)

实际上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
    ...
    }
}

希望有所帮助...