计算线性布局的空白区域

Calculate the empty area of a linear layout

我想构建一个接收 LinearLayout(或另一个视图)并计算其中剩余的空 space 的通用函数,这样我就知道我要放多少 space进去

主要目的是设置广告,示例:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:ads="http://schemas.android.com/apk/res-auto"

    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/mainView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"

    tools:context=".activity.MainActivity">


        <TextView
            android:layout_width="match_parent"
            android:layout_height="@dimen/profilePhotoRadius"
 />

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="@dimen/smallMargin"
            android:layout_marginTop="@dimen/smallMargin"
 />
<!-- bunch of other stuff here -->
        <com.google.android.gms.ads.AdView
            android:id="@+id/adView"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:layout_alignParentBottom="true"/>
</LinearLayout>

然后在我的代码中

   @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 this.adView = (AdView) findViewById(R.id.adView);
        if (this.adView != null) {


            int width =   this.adView.getMeasuredWidth();
            int height = this.adView.getHeight();
}

但 运行 此代码 widthheight 始终为零...我尝试使用 getWidth() 结果始终为零

我怎样才能得到真正的价值?

onWindowFocusChanged (boolean hasFocus)方法中尝试。
来自文档:

This is the best indicator of whether this activity is visible to the user

OnCreate() 中,您只是在膨胀布局。 UI 尚未调整大小并在屏幕上布局 yet.You 调用 getWidth()getHeight() 为时过早。 你可以试试这个:

 @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 this.adView = (AdView) findViewById(R.id.adView);
 this.adView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                touchView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
            }
            else {
                touchView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
            }

             float Width = this.adView.getWidth();
             float Height =this.adView.getHeight();
            ...
        }
    });