Java getHeight和getMeasuredHeight返回0,即使在Runnable中也是如此

Java getHeight和getMeasuredHeight返回0,即使在Runnable中也是如此,java,android,return,runnable,measurement,Java,Android,Return,Runnable,Measurement,因此,我搜索了所有getHeight/Widt问题帖子,并尝试了不同的方法来解决问题(如globalLayoutListener或Runnable),等待,直到FrameLayout被创建。。。但我的getHeight仍然返回0。 这就是我现在的代码: private void zurechtruecken() { int n=1; spB =(FrameLayout) findViewById(R.id.spielbereich); spB.post(new Run

因此,我搜索了所有getHeight/Widt问题帖子,并尝试了不同的方法来解决问题(如globalLayoutListener或Runnable),等待,直到FrameLayout被创建。。。但我的getHeight仍然返回0。 这就是我现在的代码:

private void zurechtruecken() {
    int n=1;

    spB =(FrameLayout) findViewById(R.id.spielbereich);

    spB.post(new Runnable(){
        @Override
        public void run(){

            spielBh=spB.getMeasuredHeight();
            spielBb=spB.getMeasuredWidth();
        }
    });
这是我与GlobalLayoutListener的代码:

private void zurechtruecken() {
    int i=24;
    int n=1;

    mView = findViewById(R.id.spielbereich);
    mView.getViewTreeObserver().addOnGlobalLayoutListener( 
        new OnGlobalLayoutListener(){

            @Override
            public void onGlobalLayout() {
                mView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                spielBh=mView.getHeight();
                spielBb=mView.getWidth();
                Log.i("!",Integer.toString(spielBh));
                Log.i("!",Integer.toString(spielBb));


            }
        });
“removeGlobalLayoutListener(this)”已被删除。(已弃用)

这可能很重要,我正在测量一个框架布局


谢谢你的帮助!!
Botti560

我以前也遇到过类似的麻烦。如果所有其他方法都失败,请在您自己的类中扩展FrameLayout,并在onMeasure方法中获取高度/宽度值。例如:

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

    super.onMeasure(widthMeasureSpec, heightMeasureSpec);

    int height = MeasureSpec.getSize(heightMeasureSpec);

}
也可以通过以下方式轻松地将其放入XML布局中:

<com.yourdomain.yourappname.FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" > ...
。。。

framelayout的可见性是否设置为已消失?是否应设置为已消失-它在您尝试使用onfinishflate()时设置为可见不,可见是正确的。我在onCreate中setContentView之后调用方法zurechtruecken,这可能是问题吗?很好!我会尝试一下,所以你的意思是,我应该创建另一个类,来测量frameLayout?(对不起,我对编程很陌生)或者我可以在onCreate之后调用方法Zurechtrucken吗?(但也可以使用runable?)是的,你会创建一个新类,在其中扩展frameLayout。在其中,可以有高度/宽度字段,并在onMeasure中指定它们,如图所示。由于高度/宽度是字段,您可以在活动类中获取它们的值。可能有一种更简单的方法,但是如果其他方法都失败了,那么这个方法就行了。所以我只是在所有内容都手动显示(使用onClick)后尝试获取高度,但高度仍然返回0