Android 计算线性布局的空白区域
我想构造一个接收LinearLayout(或另一个视图)的通用函数,并计算其中剩余的空白空间,这样我就知道有多少空间可以容纳某些内容 其主要目的是设置广告,例如:Android 计算线性布局的空白区域,android,android-linearlayout,dimensions,Android,Android Linearlayout,Dimensions,我想构造一个接收LinearLayout(或另一个视图)的通用函数,并计算其中剩余的空白空间,这样我就知道有多少空间可以容纳某些内容 其主要目的是设置广告,例如: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:ads="http://schemas.android.com/apk/r
<?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>
但是运行此代码时,宽度和高度始终为零。。。我尝试使用getWidth()
,结果总是零
如何获取实际值?请在WindowFocusChanged(boolean hasFocus)方法中尝试
从文档中: 这是该活动是否对用户可见的最佳指示器 使用者 在
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();
...
}
});
在onCreate中,当充气未完成时,所有尺寸均为0,它们仅在onLayout/onMeasure后具有值,请检查viewtreeobserver解决方案是否适用于您奇怪的问题。。。。没有xml中的
adview
,有什么方法可以做到这一点吗?如果我把所有的东西都放在线性布局中,有没有办法只留下空间?
@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();
...
}
});