我想构造一个通用函数,它接收 LinearLayout (或另一个 View )并计算其中剩余的空白空间,所以我知道我需要在其中容纳多少空间
它的主要目的是设置广告,例如:
<?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();
}
但运行此代码宽度
和高度
始终为零...我尝试使用getWidth()
,结果始终为零
如何获得真正的值(value)?
最佳答案
在OnCreate()
中,您只是在膨胀布局。 UI 尚未调整大小并在屏幕上布局。您过早调用 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();
...
}
});
关于android - 计算线性布局的空白区域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51271218/